Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading