python - 如何在 for 循环中创建嵌套字典(不使用 defaultdict)?

标签 python nested

我的输入如下所示:

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/

相关文章:

javascript - JS : Convert xml data to dot array notation

c - 指向全局嵌套结构的函数

python - 使用嵌套 for 和 if 循环时加快 Python 速度

python - 如何使用 Spawning 部署 Django

python - 使用 gae-sessions 检索存储在其他 session 中的信息

python - 在 pandas 数据框中创建增量数字列

python - 嵌套循环问题___>

ruby-on-rails - Rails 没有路由错误,而 rake routes 给出了路由

python - Selenium - 选择字段不会通过远程 Webdrive 保存

python - 如果我在我的 Flask 应用程序中使用 SimpleCache 会出什么问题