2012-10-31 85 views
4

我想自動將密鑰添加到Python字典中,如果它們不存在的話。 例如,自動將密鑰添加到Python字典

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

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

如何,如果不存在,我自動創建密鑰?

+0

egidra = EGIdrA = SC2? +1 on name alone – RocketDonkey

+0

@RocketDonkey yup haha​​ – egidra

回答

23

使用collections.defaultdict

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

my_dict = recursively_default_dict() 
my_dict['a']['b'] = 'c' 
+1

我早上太慢了+1 –

+0

'recursively_default_dict = lambda:defaultdict(recursively_default_dict)' – 2015-01-11 20:56:36

+1

@ X.Jacobs:「稀疏比密集好。可讀性計數。「 - [Python的禪](https://www.python.org/dev/peps/pep-0020/) – icktoofay