Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/blackberry/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在python中搜索嵌套的dict/array结构以添加子ct?_Python - Fatal编程技术网

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

如何在python中搜索嵌套的dict/array结构以添加子ct?,python,Python,如果我有以下python dict“mydict”: 如果我有另一个dict“newdict”: 如何/是否可能编写一个函数,该函数包含两个参数(“要添加到的当前词典”、“我要添加的dict”、“要插入的foldername”),以便在使用以下参数调用函数后: desiredfunction(mydict, newdict, "subsubfolder") 我希望该函数能够搜索我现有的“mydict”以找到适当的“files”数组来附加“newdict” 最好的方法是什么?我不知道如何/如果有

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

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

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

desiredfunction(mydict, newdict, "subsubfolder")
我希望该函数能够搜索我现有的“mydict”以找到适当的“files”数组来附加“newdict”

最好的方法是什么?我不知道如何/如果有可能搜索现有的字典结构,在嵌套字典的多个级别内搜索以适当地插入新的dict,在此之前,非常感谢您的帮助。

如果您知道形状(嵌套级别的数量、类型等)对于数据结构,您只需编写一个包含适当数量for循环的过程,以迭代数据结构并找到键

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

编辑:哦,你想在旧词典中添加新词典。我以为你想在新词典中添加旧词典中的内容

例如,如果你想在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循环

example = {0: {'a': 'dummy'}, 1: {'b': {'z': 'dummy'}}}
replacement = 'something'
path = [1, 'b', 'z']

parent = example
while path:
    key = path.pop(0)
    if path:
        parent = parent[key]
    else:
        parent[key] = replacement

print example

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

如何递归搜索嵌套dict并在该点插入,而无需硬编码?您能否提供一个基本函数,演示如何在保留对您所在数组的级别,以便在该点插入?据我所知,python似乎不支持这种引用。您的示例假设旧dict只有一个级别…如果有3个级别或4个级别,您的示例代码将无法工作。如果您不必硬编码for循环的数量..即m我编辑了我的文章,其中包含了一段代码片段,其中包含了您要查找的内容。
mydict = {
       "folder": "myfolder",
       "files": [
    { "folder": "subfolder",
    "files": []
    },
    { "folder": "anotherfolder",
    "files": [
    { "folder": "subsubfolder",
    "files": [
{
"folder":"newfolder"
"files":[]
}
]
    },
    { "folder": "subotherfolder",
    "files": []
    }
    ]
    },
         ]
    }
example = {0: {'a': 'dummy'}, 1: {'z': 'dummy'}}
for thing1 in example:
    for thing2 in thing1:
        if thing2 == 'z':
            example[thing1][thing2] = 'something'
example = {0: {'a': 'dummy'}, 1: {'b': {'z': 'dummy'}}}
replacement = 'something'
path = [1, 'b', 'z']

parent = example
while path:
    key = path.pop(0)
    if path:
        parent = parent[key]
    else:
        parent[key] = replacement

print example