如何在python中搜索嵌套dict/array结构以添加子ct?

2024-10-03 11:12:32 发布

您现在位置:Python中文网/ 问答频道 /正文

如果我有以下python dict“mydict”:

mydict = {
       "folder": "myfolder",
       "files": [
    { "folder": "subfolder",
    "files": []
    },
    { "folder": "anotherfolder",
    "files": [
    { "folder": "subsubfolder",
    "files": []
    },
    { "folder": "subotherfolder",
    "files": []
    }
    ]
    },
         ]
    }

如果我有另一个词“newdict”:

^{pr2}$

如何/有可能编写一个包含两个参数的函数(“要添加到的当前词典”、“要添加的dict”、“要插入的foldername”,以便在使用以下参数调用函数后:

desiredfunction(mydict, newdict, "subsubfolder")

我希望函数搜索我现有的“mydict”以查找适当的“files”数组以附加“newdict”。在

mydict = {
       "folder": "myfolder",
       "files": [
    { "folder": "subfolder",
    "files": []
    },
    { "folder": "anotherfolder",
    "files": [
    { "folder": "subsubfolder",
    "files": [
{
"folder":"newfolder"
"files":[]
}
]
    },
    { "folder": "subotherfolder",
    "files": []
    }
    ]
    },
         ]
    }

最好的办法是什么?我不知道如何/如果可以搜索现有的字典结构,在多个层次的嵌套字典中搜索适当地插入一个新的dict之前,谢谢帮助。在


Tags: 函数参数字典filesfolderdictmydict词典
1条回答
网友
1楼 · 发布于 2024-10-03 11:12:32

如果您知道数据结构的形状(嵌套层的数量、类型等),那么您只需编写一个包含适当数量for循环的过程来遍历数据结构并找到键。在

如果不知道数据结构的形状,可以递归地遍历数据结构,直到它为空或找到适当的键为止。在

编辑:哦,你想在旧的字典中添加一个新的dict。我以为您想在新的dict中添加一些内容。在

如果你想在口述的“z”键下插入“something”,而且你知道dict在任何时候都是什么样子的

example = {0: {'a': 'dummy'}, 1: {'z': 'dummy'}}
for thing1 in example:
    for thing2 in thing1:
        if thing2 == 'z':
            example[thing1][thing2] = 'something'

如果你不知道dict是什么样子,或者你不想硬编码for循环

^{pr2}$

其中path可以作为参数传递给遍历dict的递归过程的递归调用

相关问题 更多 >