我有一个像下面这样的字典列表。
它的结构类似于树,其中每个节点都有任意数量的子节点。我希望选择具有作为输入提供的匹配“name”的节点。
newdata = [
{'name':"Oli Bob", 'location':"United Kingdom", '_children':[
{'name':"Mary May", 'location':"Germany"},
{'name':"Christine Lobowski", 'location':"France"},
{'name':"Brendon Philips", 'location':"USA",'_children':[
{'name':"Margret Marmajuke", 'location':"Canada"},
{'name':"Frank Harbours", 'location':"Russia",'_children':[{'name':"Todd Philips", 'location':"United Kingdom"}]},
]},
]},
{'name':"Jamie Newhart", 'location':"India"},
{'name':"Gemma Jane", 'location':"China", '_children':[
{'name':"Emily Sykes", 'location':"South Korea"},
]},
{'name':"James Newman", 'location':"Japan"},
]目前我正在做这件事,使用下面的
op = []
def getInfo(list_of_dict, name):
for dict1 in list_of_dict:
if dict1["name"]==name:
op.append(dict1)
if "_children" in dict1:
getInfo(dict1["_children"], name)
getInfo(newdata, "Gemma Jane")
print(op)我想在没有外部变量(List)的情况下执行相同的操作。
当我尝试使用下面的函数做同样的事情时
def getInfo(list_of_dict, name):
for dict1 in list_of_dict:
if dict1["name"]==name:
return dict1
if "_children" in dict1:
return getInfo(dict1["_children"], name)
op = getInfo(newdata, "James Newman") 它进入一个递归循环,并不能为所有的值提供正确的输出。
有什么建议来解决这个问题吗?
发布于 2021-05-24 00:39:47
您可以使用递归生成器函数来搜索节点。例如:
def getInfo(data, name):
if isinstance(data, list):
for value in data:
yield from getInfo(value, name)
elif isinstance(data, dict):
if data.get("name") == name:
yield data
yield from getInfo(data.get("_children"), name)
for node in getInfo(newdata, "Gemma Jane"):
print(node)打印:
{'name': 'Gemma Jane', 'location': 'China', '_children': [{'name': 'Emily Sykes', 'location': 'South Korea'}]}https://stackoverflow.com/questions/67662039
复制相似问题