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

时间:2021-05-23 16:31:53

标签: python dictionary recursion tree

我有一个像下面这样的字典列表。

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

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

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

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

1 个答案:

答案 0 :(得分:2)

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

BaseUserModel

打印:

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)