Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - Flatten a dict of lists into unique values?

Tags:

python

I have a dict of lists in python:

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

I want to turn it into a list of the unique values

[58,64,80,130] 

I wrote a manual solution, but it's a manual solution. I know there are more concise and more elegant way to do this with list comprehensions, map/reduce , itertools , etc. anyone have a clue ?

content = {88962: [80, 130], 87484: [64], 53662: [58,80]} result = set({}) for k in content.keys() :     for i in content[k]:         result.add(i) # and list/sort/print just to compare the output r2 = list( result ) r2.sort() print r2 
like image 826
Jonathan Vanasco Avatar asked Oct 22 '12 16:10

Jonathan Vanasco


People also ask

How do you flatten a dictionary value in Python?

Use list comprehension to generate a non-unique list, convert it to a set to get the unique values, and then back into a sorted list. Perhaps not the most efficient, but yet another one line solution (this time with no imports). This should be the most elegant solution leveraging list/dictionary comprehension.

Is dict () and {} the same?

tl;dr. With CPython 2.7, using dict() to create dictionaries takes up to 6 times longer and involves more memory allocation operations than the literal syntax. Use {} to create dictionaries, especially if you are pre-populating them, unless the literal syntax does not work for your case.


2 Answers

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}) 
like image 133
nneonneo Avatar answered Sep 21 '22 08:09

nneonneo


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())))] 
like image 42
Jon Clements Avatar answered Sep 21 '22 08:09

Jon Clements