【发布时间】:2021-08-12 04:00:07
【问题描述】:
我有一个字典列表,如下所示。
它的结构类似于一棵树,其中每个节点都有任意数量的子节点。我想选择具有作为输入提供的匹配“名称”的节点。
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)
我想在没有外部变量(列表)的情况下执行相同的操作。
当我尝试使用下面的函数做同样的事情时
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")
它进入一个递归循环,并没有为所有值提供正确的输出。
有解决此问题的建议吗?
【问题讨论】:
标签: python dictionary recursion tree