from collections import defaultdict data = defaultdict(int) data['a'] += 2
print(data) # defaultdict(int, {'a': 2})
如果 data 是常规的字典类型,可就没法直接用 += 2,那如果我们需要两层嵌套时该怎么用呢?
1 2 3 4 5 6 7 8
data = defaultdict(defaultdict(int))
Traceback (most recent call last): File "/Users/aka/WorkSpace/venvs/django1.11/lib/python3.7/site-packages/IPython/core/interactiveshell.py", line 3331, in run_code exec(code_obj, self.user_global_ns, self.user_ns) File "<ipython-input-25-25b6aac66099>", line 1, in <module> data = defaultdict(defaultdict(int)) TypeError: first argument must be callableorNone