Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Obtaining list (or set) of unique values in nested dictionary

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)
like image 832
laszlopanaflex Avatar asked Feb 08 '23 09:02

laszlopanaflex


1 Answers

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'}
like image 152
Bhargav Rao Avatar answered Feb 12 '23 11:02

Bhargav Rao