Python:Comparing dictionaries in Python

There is already an existing function cmp() from Python 2 which can be used to compare dictionaries, but its output comes as -1,1 or 0. Which I don’t think is much helpful. In python 3, you would need to write your own cmp() function. So, I thought of writing a one which will be more clarifying and helpful to user.


def dict_compare(dict1, dict2):
dict_match = True
keys1 = list(dict1.keys())
keys2 = list(dict2.keys())
if (len(keys1) == len(keys2)):
print (“Number of keys in both dictionaries are same.”)
for i in range(len(keys1)):
values_match = False
for j in range(len(keys2)):
if keys1[i] == keys2[j]:
#print (“keys matched %s %s” %(keys1[i],keys2[j]))
if (dict1[keys1[i]] == dict2[keys2[j]]):
#print(“%s %s” %(dict1[keys1[i]],dict2[keys2[j]]))
values_match = True
break
else:
continue
if values_match == False:
dict_match = False
break
else:
continue
else:
dict_match = False
print (“Number of keys in both dictionaries are different.”)

return dict_match

dict1 = {
“key1″:”value 1”,
“key2″:”value 2”,
“key4″:”value 2”,
}
dict2 = {
“key3″ :”value 3”,
“key4″ :”value 4”,
“key1″ :”value 1”
}
dict3 = {
“key1″:”value 1”,
“key3″:”value 2”,
“key4″:”value 2”,
}

dict4 = {
“key1″:”value 1”,
“key4″:”value 2”,
“key2″:”value 2”,
}

dict_match = dict_compare(dict1,dict2)
print (dict_match)
dict_match = dict_compare(dict1,dict3)
print (dict_match)
dict_match = dict_compare(dict1,dict4)
print (dict_match)


 

Advertisements

Tags: , ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s


%d bloggers like this: