我想自動將密鑰添加到Python字典中,如果它們不存在的話。 例如,自動將密鑰添加到Python字典
a = "a"
b = "b"
c = "c"
dict = {}
dict[a][b] = C# doesn't work because dict[a] doesn't exist
如何,如果不存在,我自動創建密鑰?
我想自動將密鑰添加到Python字典中,如果它們不存在的話。 例如,自動將密鑰添加到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'
我早上太慢了+1 –
'recursively_default_dict = lambda:defaultdict(recursively_default_dict)' – 2015-01-11 20:56:36
@ X.Jacobs:「稀疏比密集好。可讀性計數。「 - [Python的禪](https://www.python.org/dev/peps/pep-0020/) – icktoofay
from collections import defaultdict
d = defaultdict(dict)
d['a']['b'] = 'c'
另外,請使用dict
時一定要小心 - 它有一個Python的含義:https://docs.python.org/2/library/stdtypes.html#dict
egidra = EGIdrA = SC2? +1 on name alone – RocketDonkey
@RocketDonkey yup haha – egidra