我想自动将键添加到Python字典(如果还不存在)。例如,
a = "a" b = "b" c = "c" dict = {} dict[a][b] = c # doesn't work because dict[a] doesn't exist
如果密钥不存在,如何自动创建密钥?
使用collections.defaultdict:
collections.defaultdict
def recursively_default_dict(): return collections.defaultdict(recursively_default_dict) my_dict = recursively_default_dict() my_dict['a']['b'] = 'c'