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'
source to share
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()))
source to share
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.
source to share