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.
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).
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())
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With