I am wondering if there is a more elegant/pythonic way to do the following. Suppose I have a nested dictionary:
orders = {'peter': {'food': 'pizza', 'drink': 'soda'}, 'paul': {'food': 'taco', 'drink': 'soda'},'mary': {'food': 'pizza', 'drink': 'water'}}
and I want to obtain a list containing the unique 'food' items for each person, I.e. ['pizza', 'taco']
is this the easiest way to do it?
foodList = []
for i in orders.keys():
foodList.append(orders[i]['food'])
s = set(foodList)
Use a set comprehension.
>>> {orders[i]['food'] for i in orders}
{'pizza', 'taco'}
If the values for food
are a list or a tuple you can use a nested loop in the set comprehension.
>>> orders = {'peter': {'food': ['pizza','fries'], 'drink': 'soda'}, 'paul': {'food': ['taco'], 'drink': 'soda'}}
>>> {j for i in orders for j in orders[i]['food']}
{'pizza', 'taco', 'fries'}
You can even use operator.itemgetter
as mentioned by Padraic.
>>> from operator import itemgetter
>>> set(map(itemgetter("food"), orders.values()))
{'pizza', 'taco'}
Similarly if the values for food are a list, you can use chain
.
>>> from itertools import chain
>>> set(chain(*map(itemgetter("food"), orders.values())))
{'pizza', 'taco', 'fries'}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With