Python Get unique values ​​from a dictionary

I want to get unique values ​​from my dictionary.

Input:

{320: [167], 316: [0], 319: [167], 401: [167], 319: [168], 380: [167], 265: [166]}

      

Desired output:

[167,0,168,166]

      

My code:

unique_values = sorted(set(pff_dict.itervalues()))

      

But I am getting this error: TypeError: unhashable type: 'list'

+3


source to share


3 answers


It's not clear why you are mapping lists of individual items as values, but you can use a list comprehension to retrieve items.

foobar = {320: [167], 316: [0], 319: [167], 401: [167], 319: [168], 380: [167], 265: [166]}
print list(set([x[0] for x in foobar.values()]))

      



If you start with direct mapping to values, the code can be much simpler.

foobar = {320: 167, 316: 0, 319: 167, 401: 167, 319: 168, 380: 167, 265: 166}
print list(set(foobar.values()))

      

+2


source


Lists don't qualify as a content candidate because they don't shake.

You can combine items into one container using itertoos.chain.from_iterable

before calling set

:



from itertools import chain

unique_values = sorted(set(chain.from_iterable(pff_dict.itervalues())))

      

Note that usage itertools

does not break your choice dict.itervalues

over dict.values

as unfolding / chaining is lazy.

+3


source


set

expect no items to be listed, so you need to create a list of items using list comprehension

In [34]: sorted(set([i[0] for i in d.values()]))
Out[34]: [0, 166, 167, 168]

      

0


source







All Articles