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

Create a list of values from nested dictionary Python

I have the following data structure:

listionary = [{'a': [{'id': 30, 'name': 'bob'}, {'id': 50, 'name':'mike'}]},
             {'b': [{'id': 99, 'name': 'guy'}, {'id': 77, 'name':'hal'}]}]

and I want to create a list of the values for each 'id' key.

ie. lst = [30, 50, 99, 77]

I know I need three iterators to traverse through the structure:

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

one to access the two parents dictionaries inside the array, another to access the lists of keys 'a' and 'b', and then a last to get the value of each id key in the nested child dictionaries

I tried

lst = [[x][y][y]['id'] for x, y, z in listionary]

but I got an error of

ValueError: not enough values to unpack (expected 3, got 1)

Is there a clean way to implement this?

>Solution :

You can do this with 3 for loops in list comprehension:

listionary = [
    {"a": [{"id": 30, "name": "bob"}, {"id": 50, "name": "mike"}]},
    {"b": [{"id": 99, "name": "guy"}, {"id": 77, "name": "hal"}]},
]

lst = [d["id"] for d in listionary for v in d.values() for d in v]
print(lst)

Prints:

[30, 50, 99, 77]

Explanation:

for d in listionary – this will iterate over all items inside list listionary ({"a":...}, {"b":...})

for v in d.values() – this will iterate over all items inside these dictionaries ([{"id:...}, {"id":...}], [...])

for d in v – this will get all dictionaries from these lists ({"id:...}, {"id":...}, ....)

d["id"] – this will get value from the key "id"

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