我的输入如下所示:
test_file = [['ref1', 'test1', 2],
['ref2', 'test1', 3],
['ref3', 'test2', 4],
['ref1', 'test2', 4],
['ref2', 'test2', 1],
['ref1', 'test1', 4],
['ref1', 'test1', 5]]
我正在尝试获取像这样的嵌套字典:
desired_output = {'ref1':{'test1':[2,5,4]},
'ref1':{'test2':[4]},
'ref2':{'test1':[3]},
'ref2':{'test2':[1]},
'ref3':{'test2':[4]}}
我尝试通过将值附加到第二个键来使用defaultdict,但是,我收到了此错误:
AttributeError: 'collections.defaultdict' object has no attribute 'append'
所以,我尝试了这个:
for entry in test_file:
nest1 = {}
try:
nest1[entry[1]].append(entry[2])
except KeyError:
nest1[entry[1]] = [entry[2]]
try:
mynestdict[entry[0]].append(nest1)
except KeyError:
mynestdict[entry[0]] = [nest1]
print(dict(mynestdict))
但是我得到了这个:
{'ref1': [{'test1': [2]}, {'test2': [4]}, {'test1': [4]}, {'test1': [5]}],
'ref2': [{'test1': [3]}, {'test2': [1]}],
'ref3': [{'test2': [4]}]}
我不熟悉嵌套字典,我真的很想了解它们,有什么建议吗?
最佳答案
我认为您正在寻找的输出是这样的,结合了重复的键:
{'ref1': {'test1': [2, 4, 5], 'test2': [4]}, 'ref2': {'test1': [3], 'test2': [1]}, 'ref3': {'test2': [4]}}
为此,只需检查嵌套键是否存在,如果不存在,则创建它们。您要求提供不使用 collections.defaultdict
的代码,并且它不会使其变得更多:
test_file = [['ref1', 'test1', 2],
['ref2', 'test1', 3],
['ref3', 'test2', 4],
['ref1', 'test2', 4],
['ref2', 'test2', 1],
['ref1', 'test1', 4],
['ref1', 'test1', 5]]
d = {}
for el in test_file:
if el[0] not in d:
d[el[0]] = {}
if el[1] not in d[el[0]]:
d[el[0]][el[1]] = []
d[el[0]][el[1]].append(el[2])
print(d)
关于python - 如何在 for 循环中创建嵌套字典(不使用 defaultdict)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75901065/