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