说我有一个简单的字典d={'a':1}
我希望运行d['b']['c'] = 2
行,但我不能,我得到:KeyError: 'b'
我不想先用空字典插入b
,因为在大多数情况下,此字典将包含b
,除了c
以外,还有更多值。
是否有一种优雅的方法可以使我的最终词典是:
d = {'a':1,
'b':{'c':2}}
defaultdict对您足够吗?
from collections import defaultdict
d = defaultdict()
d['a'] = 1
print(d) # this gives back: defaultdict(None, {'a': 1})
d['b'] = {'c':2}
print(d) # this gives back: defaultdict(None, {'a': 1, 'b': {'c': 2}})
有关defaultdict的更好示例:
s = 'mississippi'
d = defaultdict(int)
for k in s:
d[k] += 1
d.items() # this gives back: [('i', 4), ('p', 2), ('s', 4), ('m', 1)]
首次遇到字母时,映射中将缺少它,因此default_factory函数调用int()以提供默认计数零。然后,递增操作将为每个字母建立计数。
好吧,如果您不想先分配一个空的字典以删除任何内容,则可以先检查该字典是否在这里,这不仅是一行,而且我认为很清楚:
d ={'a':1}
b = d.get('b', {})
b['c'] = 2
d['b'] = b