Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 928
user3067923 Avatar asked Jan 29 '23 02:01

user3067923


2 Answers

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).

like image 74
Reblochon Masque Avatar answered Jan 31 '23 21:01

Reblochon Masque


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())
like image 26
miradulo Avatar answered Jan 31 '23 23:01

miradulo