Python - Flatten a dict of lists into unique values?

In python3.7 you can use a combination of .values, and chain.

from itertools import chain
sorted(set(chain(*content.values())))
# [58, 64, 80, 130]

# another option is `itertools.groupby`
from itertools import groupby
[k for k, g in groupby(sorted(chain(*content.values())))]

In python2.7

from itertools import chain
sorted(set(chain.from_iterable(content.itervalues())))
# [58, 64, 80, 130]

# another option is `itertools.groupby`
[k for k, g in groupby(sorted(chain.from_iterable(content.itervalues())))]

sorted(set(val
            for row in content.itervalues()
                for val in row))

set gets us all the distinct values (like a dictionary, but without the overhead of storing values). sorted then just takes the created set and returns a list sorted in ascending order.


use set() and itertools.chain():

In [83]: content = {88962: [80, 130], 87484: [64], 53662: [58,80]}

In [84]: from itertools import chain

In [94]: x=set(chain(*content.values()))

In [95]: x
Out[95]: set([58, 64, 80, 130]) # a set, the items may or may not be sorted

In [96]: sorted(x)         #convert set to a sorted list
Out[96]: [58, 64, 80, 130]

Double set comprehension:

Python 3:

sorted({x for v in content.values() for x in v})

Python 2:

sorted({x for v in content.itervalues() for x in v})

Tags:

Python