nanjun
nanjun

Reputation: 133

How to get all values with the same key in a nested dictionary in Python?

I have a nested dictionary mydict = {'Item1': {'name': 'pen', 'price': 2}, 'Item2': {'name': 'apple', 'price': 0.69}}. How do I get all the values of the same key? For example, I want to get a list [2, 0.69] corresponding to the key 'price'. What is the best way to do that without using a loop?

Upvotes: 3

Views: 1439

Answers (1)

Jan Stránský
Jan Stránský

Reputation: 1691

I doubt it is possible literally without any loop, so here is a solution using list coprehension:

mydict = {'Item1': {'name': 'pen', 'price': 2}, 'Item2': {'name': 'apple', 'price': 0.69}}
output = [v["price"] for v in mydict.values()]
print(output)

Or a solution using map:

output = list(map(lambda v: v["price"], mydict.values()))
print(output)

All outputs:

[2, 0.69]

Upvotes: 3

Related Questions