gpt4 book ai didi

python - 在遍历字典时使用递归函数来填充一个空的字典列表

转载 作者:太空宇宙 更新时间:2023-11-04 04:21:35 24 4
gpt4 key购买 nike

我有一个字典列表,它来自 JSON 文件。这是一个 JSON 文件(有意简化):

[
{
"one":{
"private":{
"resource":"qwerty"
},
"children":[
"test"
],
"public":{
"-name":"gf"
},
"parents":[
"twenty"
],
"id":"one",
"properties":{
"COLOR":{
"-type":"string"
},
"H":{
"-type":"double"
},
"TO_NOTIFY":{
"-type":"string"
},
"environment":{
"-type":"string"
},
"EMAIL_TO":{
"-type":"string"
},
"W":{
"-type":"double"
},
"Y":{
"-type":"double"
},
"X":{
"-type":"double"
}
}
}
},
{
"two":{
"private":{
"resource":"qwerty"
},
"children":[
"test"
],
"public":{
"-name":"gf"
},
"parents":[
"one"
],
"id":"two",
"properties":{
"COLOR":{
"-type":"string"
},
"H":{
"-type":"double"
},
"TO_NOTIFY":{
"-type":"string"
},
"environment":{
"-type":"string"
},
"EMAIL_TO":{
"-type":"string"
},
"W":{
"-type":"double"
},
"Y":{
"-type":"double"
},
"X":{
"-type":"double"
}
}
}
},
{
"three":{
"private":{
"resource":"qwerty"
},
"children":[
"test"
],
"public":{
"-name":"gf"
},
"parents":[
"two"
],
"id":"three",
"properties":{
"COLOR":{
"-type":"string"
},
"H":{
"-type":"double"
},
"TO_NOTIFY":{
"-type":"string"
},
"environment":{
"-type":"string"
},
"EMAIL_TO":{
"-type":"string"
},
"W":{
"-type":"double"
},
"Y":{
"-type":"double"
},
"X":{
"-type":"double"
}
}
}
},
{
"four":{
"private":{
"resource":"qwerty"
},
"children":[
"test"
],
"public":{
"-name":"gf"
},
"parents":[
"one"
],
"id":"four",
"properties":{
"COLOR":{
"-type":"string"
},
"H":{
"-type":"double"
},
"TO_NOTIFY":{
"-type":"string"
},
"environment":{
"-type":"string"
},
"EMAIL_TO":{
"-type":"string"
},
"W":{
"-type":"double"
},
"Y":{
"-type":"double"
},
"X":{
"-type":"double"
}
}
}
}
]

我的目标:更新当前的 JSON(您在文件中看到的内容),使其仅包含请求的条目。 Requested 这里的意思是用户给我一些需要的条目,比方说 three。我想将 three 附加到新列表中。此外,我需要找到 three 的父 parents,并将其也附加到该列表中。我还需要找到后续条目的父级等等。

我该怎么做?我为此使用递归吗?这是我目前所拥有的:

import json

with open('/home/intern/nbf/1.json') as f:
data = json.load(f)

# Finds a parent of a node (and of subsequent nodes if any)
def find_parent(node, data = data):

l = []

for i in range(len(data)):
for k in data[i]:
if k == node:
l.append(data[i])

find_parent('three')

我仍然缺少检查 parents 并将它们添加到列表 l 的部分。

最佳答案

完成“三”的过程后,您将再次调用该函数(使用相同的列表),但使用“三”的两个父项。如果你有循环,你必须要小心,因为那样这将永远不会终止。

def find_parent(node, data, l=None):
if l is None:
l = []

for i in range(len(data)):
for k in data[i]:
print(k)

if k == node:
l.append(data[i])
for parent in data[i][k]["parents"]:
find_parent(parent, data, l)
return l

关于python - 在遍历字典时使用递归函数来填充一个空的字典列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54414570/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com