我想自动将密钥添加到Python字典中,如果它们已经不存在的话。 例如,
a = "a"
b = "b"
c = "c"
dict = {}
dict[a][b] = c # doesn't work because dict[a] doesn't exist
如果密钥不存在,如何自动创建密钥?
答案 0 :(得分:24)
def recursively_default_dict():
return collections.defaultdict(recursively_default_dict)
my_dict = recursively_default_dict()
my_dict['a']['b'] = 'c'
答案 1 :(得分:1)
from collections import defaultdict
d = defaultdict(dict)
d['a']['b'] = 'c'
另外,使用dict
时请小心 - 它在python中有意义:https://docs.python.org/2/library/stdtypes.html#dict
答案 2 :(得分:0)
对于简短的脚本,您也可以使用此衬纸:
d = {}
d.setdefault(a, {})[b] = c