Home > Blockchain >  Get intersection of all values from a dictionary with lists
Get intersection of all values from a dictionary with lists

Time:10-12

I have a dictionary which contains key-value pairs where the key is a string and the value is stored as a list.

I am looking to get the intersection of all the elements in the lists of each entry in the dictionary.

For instance, if I had a dictionary like this:

athletes = {"athlete_A" : [16,43,34,23], "athlete_B": [23,60,80,75]}

I would like to get the list [23]. I can find solutions on intersection of dictionaries, but I don't seem to find how to work with only the values of a dict.

CodePudding user response:

You can use functools.reduce and set intersection:

from functools import reduce

reduce(set.intersection, map(set, athletes.values()))
# {23}

If there are duplicates within your lists and you want to catch all (e.g. if two 23s occur in each list), you can use Counter intersection instead:

from collections import Counter

[*reduce(Counter.__and__, map(Counter, athletes.values())).elements()]
# [23]

CodePudding user response:

Create set from the first athlete's list

A_as_set = set(athletes['athlete_A'])
intersection = A_as_set.intersection(athletes['athlete_B'])
intersection_as_list = list(intersection)

Source HERE for intersection and HERE for dictionary

  • Related