user3067923
user3067923

Reputation: 447

count how many times keys repeat between dictionaries in python

How do I check to see how many times the keys in one dict1 exist in dict2. If the keys of dict1 exist in dict2 a variable, val, with an initial value of 4 should be subtracted based on how many times the keys are found.

For example dict1 looks like this

print dict1
{(2, 0): 3, (3, 1): 0, (1, 1): 2, (2, 2): 1} 

and dict2 looks like this

print `dict2`
{(2, 0): 323, (3, 1): 32, (10, 10): 21, (20, 2): 100} 

Since there are two repeat keys between the dicts,val should be equal to 2.

if dict2 looks identical to dict1, then val should be 0.

Also, dict1 will always be the same size, but dict2 can get quite large, so a fast lookup method would be ideal. Lastly, the values of dicts here don't really mean anything.

Upvotes: 4

Views: 805

Answers (4)

miradulo
miradulo

Reputation: 29680

Since dict_keys are already set-like, you can simply use

len(dict1.keys() & dict2.keys())

That is for Python 3. In Python 2, the equivalent view object is dict.viewkeys(), which you'd use similarly.

len(dict1.viewkeys() & dict2.viewkeys())

Upvotes: 4

Akavall
Akavall

Reputation: 86128

This will work in Python 2 and 3: len(set(dict1).intersection(dict2))

In [1]: dict1 = {(2, 0): 3, (3, 1): 0, (1, 1): 2, (2, 2): 1}

In [2]: dict2 = {(2, 0): 323, (3, 1): 32, (10, 10): 21, (20, 2): 100}

In [3]: len(set(dict1).intersection(dict2))
Out[3]: 2

Upvotes: 0

Reblochon Masque
Reblochon Masque

Reputation: 36652

Using set intersection:

d1 = {(2, 0): 3, (3, 1): 0, (1, 1): 2, (2, 2): 1} 
d2 = {(2, 0): 323, (3, 1): 32, (10, 10): 21, (20, 2): 100} 

sd1 = set(d1.keys())
sd2 = set(d2.keys())
len(sd1.intersection(sd2))

Edit: Because key views are already set-like, so you can do d1.keys() & d2.keys() directly. Note that .keys() is a very cheap call because it simply provides an alternative interface to the existing dict structure (Credits to @PM2RING in the comments).

Upvotes: 4

Prune
Prune

Reputation: 77827

Make sets out of the list of keys in each dict. Find the intersection and union of those sets. union - intersection gives you the set of differences. If that's 0, then you return 0; otherwise, return the size of the intersection.

Upvotes: 0

Related Questions