使用循环过滤嵌套字典的列表



我有一个dict列表,如下所示。

它的结构类似于一棵树,其中每个节点都有任意数量的子节点。我想选择一个节点,该节点具有作为输入提供的匹配的"名称"。

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")  

它进入递归循环,并不能为所有值提供正确的输出。

有什么解决这个问题的建议吗?

您可以使用递归生成器函数来搜索节点。例如:

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'}]}

最新更新