Skip to content
Advertisement

get all values by a specific key in a deep nested dict using python

{
    "id": 1,
    "name": "Test",
    "fils": [
        {"id": 2, "name": "Test", "fils": []},
        {"id": 4, "name": "Test", "fils": []},
        {
            "id": 5,
            "name": "Test",
            "fils": [
                {
                    "id": 12,
                    "name": "Test",
                    "fils": [{"id": 14, "name": "test", "fils": []}],
                }
            ],
        },
    ],
}

so my goal is to get all the id’s which are [1,2,4,5,12,14]. is there any way to get that using a recursive function or in an another way?

Advertisement

Answer

You can use recursion. If dct is your dictionary from the question, then:

def get_ids(d):
    if isinstance(d, dict):
        for k, v in d.items():
            if k == "id":
                yield v
            else:
                yield from get_ids(v)
    elif isinstance(d, list):
        for v in d:
            yield from get_ids(v)


ids = list(get_ids(dct))
print(ids)

Prints:

[1, 2, 4, 5, 12, 14]
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement