user4637416
user4637416

Reputation:

How do I find common items from Python dictionary values?

Say, I have a dictionary D:

D = {'A': {1, 2, 3}, 'B': {2, 4, 5}, 'C': {1, 2, 7}}

Now I want to have all common items from D's values, which would be 2. I tried to use set.intersection but it did not work out.

Upvotes: 3

Views: 6739

Answers (4)

Padraic Cunningham
Padraic Cunningham

Reputation: 180391

If you go with reduce the most efficient way is to use operator.and_

from functools import reduce
from operator import and_

D = {'A': {1, 2, 3}, 'B': {2, 4, 5}, 'C': {1, 2, 7}}

print(reduce(and_, D.values()))

But set.intersection will be hard to beat:

In [89]: from functools import reduce

In [90]: from operator import and_

In [91]: timeit reduce(lambda x, y: x & y, D.values())
1000 loops, best of 3: 221 µs per loop

In [92]: timeit reduce(and_,D. values())
10000 loops, best of 3: 170 µs per loop

In [93]: timeit set.intersection(*D.values())
10000 loops, best of 3: 155 µs per loop

Upvotes: 0

Eugene Yarmash
Eugene Yarmash

Reputation: 149736

For the sake of variety, you could also use reduce():

>>> D = {'A': {1, 2, 3}, 'B': {2 ,4, 5}, 'C': {1, 2, 7}}
>>> reduce(lambda x, y: x & y, D.values())  # or use operator.and_ instead of lambda
{2}

reduce() is a built-in function in Python 2.x, but needs to be imported from the functools module in Python 3.x.

Upvotes: 2

TheLazyScripter
TheLazyScripter

Reputation: 2665

If you are only looking for common values in each dictionary and not looking for a value that is in each dict then the following code will work! Not saying that this is the fastest or the best approach, but it works! Returns a list of all duplicate values across the embedded dicts!

def findCommon(data):

    flipped = {}
    out = []

    for i in data:
        for value in data[i]:
            if value not in flipped:
                flipped[value] = [i]
            else:
                flipped[value].append(i)
    for i in flipped:
        if len(flipped[i]) > 1:
            out.append(i)
    return out

Upvotes: 0

Iron Fist
Iron Fist

Reputation: 10951

Simply, use intersection method of set:

>>> set.intersection(*D.values())
{2}

D.values() will return a list of your dictionary values which are already sets, then *D.values() will unpack this list and pass it to intersection method of set class

Upvotes: 6

Related Questions