赞
踩
dic = {"a":1,"b":2, "c":3, "d":4}
key = "e"
value = 0
if key in dic:
value = dic[key]
else:
value = 0
value = dic.get("e",0)
# 同时也可以将列表作为默认值
value2 = dic.get("e",[1,2,3])
value
0
value2
[1, 2, 3]
words = ["apple","banana","airline","bank","panda"]
by_letters = dict()
for word in words:
first_letter = word[0]
if first_letter in by_letters:
by_letters[first_letter].append(word)
else:
by_letters[first_letter] = [word]
by_letters
{'a': ['apple', 'airline'], 'b': ['banana', 'bank'], 'p': ['panda']}
by_letters = {}
for word in words:
by_letters.setdefault(word[0],[]).append(word)
by_letters
{'a': ['apple', 'airline'], 'b': ['banana', 'bank'], 'p': ['panda']}
from collections import defaultdict
by_letters = defaultdict(list)
for word in words:
by_letters[word[0]].append(word)
by_letters
defaultdict(list,
{'a': ['apple', 'airline'],
'b': ['banana', 'bank'],
'p': ['panda']})
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。