erija
erija

Reputation: 87

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'

Upvotes: 5

Views: 18900

Answers (3)

Moses Koledoye
Moses Koledoye

Reputation: 78564

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.

Upvotes: 4

Rahul K P
Rahul K P

Reputation: 16081

set expect an elements not list of list, So you have to create a list of elements using list comprehension

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

Upvotes: 0

merlin2011
merlin2011

Reputation: 75649

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()))

Upvotes: 2

Related Questions