众所周知,在Python中如果访问字典中不存在的键,会引发KeyError异常(JavaScript中如果对象中不存在某个属性,则返回undefined)。但是有时候,字典中的每个键都存在默认值是非常方便的。
from collections import defaultdict
s = [('red', 1), ('blue', 2), ('red', 3), ('blue', 4), ('red', 1), ('blue', 4)]
d = defaultdict(set)
for k, v in s:
d[k].add(v)
print(d)
s2 = 'Chinese'
d2 = defaultdict(int)
for k2 in s2:
d2[k2] += 1
print(d2)
print(d2['s'])
输出:
defaultdict(<type 'set'>, {'blue': set([2, 4]), 'red': set([1, 3])})
defaultdict(<type 'int'>, {'C': 1, 'e': 2, 'i': 1, 'h': 1, 'n': 1, 's': 1})
1
参考:
https://www.cnblogs.com/jidongdeatao/p/6930325.html
https://www.jb51.net/article/115578.htm
网友评论