小编典典

自动将密钥添加到Python字典

python

我想自动将键添加到Python字典(如果还不存在)。例如,

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

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

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


阅读 317

收藏
2021-01-20

共1个答案

小编典典

使用collections.defaultdict

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

my_dict = recursively_default_dict()
my_dict['a']['b'] = 'c'
2021-01-20