一尘不染

自动将密钥添加到Python字典

python

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

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

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

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


阅读 283

收藏
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