Iterate through all distinct dictionary values in a list of dictionaries

792 Views Asked by At

Assuming a list of dictionaries, the goal is to iterate through all the distinct values in all the dictionaries.

Example:

d1={'a':1, 'c':3, 'e':5}
d2={'b':2, 'e':5, 'f':6}
l=[d1,d2]

The iteration should be over 1,2,3,5,6, does not matter if it is a set or a list.

6

There are 6 best solutions below

0
On BEST ANSWER

You can use set with a comprehension:

d1 = {'a':1, 'c':3, 'e':5}
d2 = {'b':2, 'e':5, 'f':6}
L = [d1, d2]

final = set(j for k in L for j in k.values())
# {1, 2, 3, 5, 6}
0
On

You can use set.union to iterate over distinct values:

res = set().union(*(i.values() for i in (d1, d2)))

# {1, 2, 3, 5, 6}
0
On

Using set

Ex:

from itertools import chain
d1={'a':1, 'c':3, 'e':5}
d2={'b':2, 'e':5, 'f':6}
l=set(chain.from_iterable([d1.values(),d2.values()]))
print( l )

Output:

set([1, 2, 3, 5, 6])
  • chain.from_iterable to flatten the list
0
On

Simple solution using itertools.chain and a generator expression:

from itertools import chain

set(chain.from_iterable(d.values() for d in l))
0
On
print list(set().union(a, b))

Pretty straight forward

0
On
from functools import reduce
print(reduce(set.union, map(set, map(dict.values, l))))

This outputs:

{1, 2, 3, 5, 6}