1

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?

1 Answer 1

1

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"

Sign up to request clarification or add additional context in comments.

2 Comments

Can you please explain the logic of the for loops? Thanks
@Wiseface I've added some explanation.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.