2017-12-22 10 views
0

고유 한 데이터를 저장하기 위해 파이썬에서 중첩 된 사전을 처리하려고합니다. 그러나, 나는 그것을하는 옳은 방법이 무엇인지 모른다. 나는 다음을 시도했다 :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 대답은 중첩 된 DICT를 설정하고 접속하시면 보여 임의의 깊이를 필요로하지 않는 경우.

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}})