Python3.6 4级词典给出了KeyError

时间:2017-12-22 08:27:19

标签: python python-3.x dictionary defaultdict

我想在python中处理嵌套字典以存储唯一数据。但是,我不知道正确的方法。我尝试了以下方法:

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

但它会导致KeyError。 这样做的正确方法是什么?

2 个答案:

答案 0 :(得分: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}})

答案 1 :(得分: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答案会演示设置嵌套字典并访问它。