Count how many times keys are repeated between dictionaries in python

How to check how many times keys in one dict1exist in dict2. If the keys dict1exist in the dict2variable,, valwith the initial value 4should be subtracted depending on how many times the keys were found.

An example is dict1as follows

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

and dict2looks like this:

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

Since there are two snooze keys between dicts, it valshould be equal 2.

if dict2looks identical dict1then valshould be 0.

, dict1 , dict2 , . , dicts .

+4
4

:

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

: , d1.keys() & d2.keys() . , .keys() - , dict (Credits to @PM2RING ).

+4

dict_keys ,

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

Python 3. Python 2 dict.viewkeys(), .

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

Make a list from a list of keys in each dict. Find the intersection and union of these sets. union - intersectiongives you a set of differences. If it is 0, then you return 0; otherwise return the intersection size.

0
source

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
0
source

Source: https://habr.com/ru/post/1690105/


All Articles