Home > Software design >  Create a list of values from nested dictionary Python
Create a list of values from nested dictionary Python

Time:02-14

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:

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?

CodePudding user response:

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"

  • Related