传统方式

方式一: 使用 try-except

1
2
3
4
5
6
try:
result[key]
except KeyError:
result[key] = 0
finally:
result[key] += 1

方式二: 使用 has_key 或 in

1
2
3
4
if foo.has_key(bar):
foo[bar] += 1
else:
foo[bar] = 1

新方式

方式一: 使用 defaultdict

1
2
3
from collections import defaultdict
foo = defaultdict(int)
foo[bar] += 1

方式二: 使用 get 方法

1
foo[bar] = foo.get(bar, 0) + 1

参考链接