Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python Get the unique values from a dictionary

I want to get the 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'm getting this error : TypeError: unhashable type: 'list'

like image 959
erija Avatar asked May 11 '17 13:05

erija


2 Answers

Lists do not qualify as candidate set content because they are unhashable.

You can merge the 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 using itertools does not violate your choice of dict.itervalues over dict.values as the unwrapping/chaining is done lazily.

like image 147
Moses Koledoye Avatar answered Sep 29 '22 14:09

Moses Koledoye


It is not clear why you are mapping to single-item lists as values, but you can use a list comprehension to extract the elements.

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 out by mapping directly to values though, 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()))
like image 29
merlin2011 Avatar answered Sep 29 '22 14:09

merlin2011