Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to compare two dictionaries to check if a key is present in both of them

Tags:

python

I am trying to compare two dictionaries and check if each key in dict1 is present(or not) in either of dict2 or dict3 using the below logic? Is there a better way to check if any of the keys in dict1 are present in dict2 or dict3 and get the corresponding value?

dict1 = {'1234': 'john','5678': 'james'};
dict2 = {'1234': 'technician'};
dict3 = {'5678': '50.23'};

shared_keys1 = set(dict1).intersection(dict2)

shared_keys2 = set(dict1).intersection(dict3)

for key in shared_keys1:
    print( "Found Shared Key:{0}".format(key) )
    print( "dict1['{0}']={1}".format(key,dict2[key]) )


for key in shared_keys2:
    print( "Found Shared Key:{0}".format(key) )
    print( "dict1['{0}']={1}".format(key,dict3[key]) )

OUTPUT:-

Found Shared Key:1234
dict1['1234']=technici
Found Shared Key:5678
dict1['5678']=50.23

2 Answers

in on a dict will return if a key is present in a dictionary:

>>> a = {'b': 1, 'c': '2'}
>>> 'b' in a
True
>>> 'd' in a
False

So your code could be written as:

dict1 = {'1234': 'john','5678': 'james'};
dict2 = {'1234': 'technician'};

for key in dict1.keys():
    print key
    if key in dict2:
        print dict1[key] + dict2[key]
    else:
        print dict1[key]

If you just want to check that the two are equal, you can do:

set(dict1) == set(dict2)
like image 164
Alex Taylor Avatar answered Sep 14 '25 09:09

Alex Taylor


shared_keys = set(dict1).intersection(dict2)

is how I would do it

>>> dict1 = {'1234': 'john','5678': 'james'}
>>> dict2 = {'1234': 'technician'};
>>> set(dict1).intersection(dict2)
set(['1234'])


>>> if set(dict1).intersection(dict2):
...     print "there is at least one key that is present in both dictionaries..."
...
there is at least one key that is present in both dictionaries...

if you wanted to check more dicts you just add them

shared_keys = set(dict1).intersection(dict2).intersection(dict3)


for key in shared_keys:
    print( "Found Shared Key:{0}".format(key) )
    print( "dict1['{0}']={1}".format(key,dict1[key]) )
    print( "dict2['{0}']={1}".format(key,dict2[key]) )
    print( "dict3['{0}']={1}".format(key,dict3[key]) )
like image 24
Joran Beasley Avatar answered Sep 14 '25 09:09

Joran Beasley