2017-12-22 11 views
0

私は、一意のデータを格納する目的で、Pythonでネストされた辞書を扱いたいと思います。しかし、私はそれを行う正しい方法がわかりません。私は以下を試しました:Python36 4レベル辞書のキーエラー

my_dict = collections.defaultdict(dict) 
my_dict[id1][id2][id2][id4] = value 

しかし、それはキーエラーの原因となります。 これを行う正しい方法は何ですか?

答えて

1

あなたはあなたがしてdefaultdictを返す関数にdefaultdictのデフォルトタイプを設定したいその後、好きなだけの深さにネストされたdefaultdictを作成したい場合同じ種類。だから少し再帰的に見えます。あなたが任意の深さを必要としない場合は

from collections import defaultdict 

def nest_defaultdict(): 
    return defaultdict(nest_defaultdict) 

d = defaultdict(nest_defaultdict) 
d[1][2][3] = 'some value' 
print(d) 
print(d[1][2][3]) 

# Or with lambda 
f = lambda: defaultdict(f) 
d = defaultdict(f) 

そしてFuji Clado's答えは、ネストされた辞書を設定し、それへのアクセスを示しています。

1

一つの単純なアプローチ

mainDict = {} 
mainDict['id1']={} 
mainDict['id1']['id2'] ={} 
mainDict['id1']['id2']['id3'] = 'actualVal' 

print(mainDict) 


# short explanation of defaultdict 

import collections 

# when a add some key to the mainDict, mainDict will assgin 
# an empty dictionary as the value 

mainDict = collections.defaultdict(dict) 

# adding only key, The value will be auto assign. 
mainDict['key1'] 

print(mainDict) 
# defaultdict(<class 'dict'>, {'key1': {}}) 

# here adding the key 'key2' but we are assining value of 2 
mainDict['key2'] = 2 
print(mainDict) 

#defaultdict(<class 'dict'>, {'key1': {}, 'key2': 2}) 


# here we are adding a key 'key3' into the mainDict 
# mainDict will assign an empty dict as the value. 
# we are adding the key 'inner_key' into that empty dictionary 
# and the value as 10 

mainDict['key3']['inner_key'] = 10 
print(mainDict) 

#defaultdict(<class 'dict'>, {'key1': {}, 'key2': 2, 'key3': {'inner_key': 10}}) 
関連する問題