Search code examples
pythonintersect

python intersect of dict items


Suppose I have a dict like:

aDict[1] = '3,4,5,6,7,8'
aDict[5] = '5,6,7,8,9,10,11,12'
aDict[n] = '5,6,77,88'

The keys are arbitrary, and there could be any number of them. I want to consider every value in the dictionary.

I want to treat each string as comma-separated values, and find the intersection across the entire dictionary (the elements common to all dict values). So in this case the answer would be '5,6'. How can I do this?


Solution

  • from functools import reduce # if Python 3
    
    reduce(lambda x, y: x.intersection(y), (set(x.split(',')) for x in aDict.values()))