pythondictionaryvalue-iteration

Iterate through all distinct dictionary values in a list of dictionaries


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.


Solution

  • 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}