5

如果它们不存在,我想自动将键添加到 Python 字典中。例如,

a = "a"
b = "b"
c = "c"

dict = {}
dict[a][b] = c # doesn't work because dict[a] doesn't exist

如果密钥不存在,如何自动创建密钥?

4

3 回答 3

27

使用collections.defaultdict

def recursively_default_dict():
    return collections.defaultdict(recursively_default_dict)

my_dict = recursively_default_dict()
my_dict['a']['b'] = 'c'
于 2012-10-31T04:30:17.540 回答
5
from collections import defaultdict
d = defaultdict(dict)
d['a']['b'] = 'c'

另外,使用时请小心dict-它在python中具有含义:https ://docs.python.org/2/library/stdtypes.html#dict

于 2017-02-18T12:00:23.910 回答
1

对于简短的脚本,您还可以使用这一行:

d = {}
d.setdefault(a, {})[b] = c
于 2020-09-20T05:07:19.607 回答