如果我有以下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之前,谢谢帮助。在
如果您知道数据结构的形状(嵌套层的数量、类型等),那么您只需编写一个包含适当数量for循环的过程来遍历数据结构并找到键。在
如果不知道数据结构的形状,可以递归地遍历数据结构,直到它为空或找到适当的键为止。在
编辑:哦,你想在旧的字典中添加一个新的dict。我以为您想在新的dict中添加一些内容。在
如果你想在口述的“z”键下插入“something”,而且你知道dict在任何时候都是什么样子的
如果你不知道dict是什么样子,或者你不想硬编码for循环
^{pr2}$其中
path
可以作为参数传递给遍历dict的递归过程的递归调用相关问题 更多 >
编程相关推荐