简体   繁体   中英

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:

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?

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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM