Python3.6 4 级字典给出 KeyError
Python3.6 4-level dictionaries giving KeyError
我想处理 python 中的嵌套字典以存储唯一数据。但是,我不知道正确的方法是什么。我尝试了以下方法:
my_dict = collections.defaultdict(dict)
my_dict[id1][id2][id2][id4] = value
但它会导致 KeyError。
这样做的正确方法是什么?
一个简单的方法
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}})
如果您想创建任意深度的嵌套 defaultdict,则需要将 defaultdict 的默认类型设置为 returns 具有相同类型的 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)
如果您不需要任何深度,那么 答案演示了如何设置嵌套字典并访问它。
我想处理 python 中的嵌套字典以存储唯一数据。但是,我不知道正确的方法是什么。我尝试了以下方法:
my_dict = collections.defaultdict(dict)
my_dict[id1][id2][id2][id4] = value
但它会导致 KeyError。 这样做的正确方法是什么?
一个简单的方法
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}})
如果您想创建任意深度的嵌套 defaultdict,则需要将 defaultdict 的默认类型设置为 returns 具有相同类型的 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)
如果您不需要任何深度,那么