I am new to Python. I have two dictionaries which share the same keys but different values for the keys. I would like to compare the two dictionaries so that I would get the numerical difference of the values for each key. For example:
dict1 = {'hi' : 45, 'thanks' : 34, 'please' : 60}
dict2 = {'hi' : 40, 'thanks' : 46, 'please' : 50}
In other words, I would like to receive a third dictionary or a list of pairs that would show the numerical difference of the values within these two dictionaries (i.e.subtracting the values of dict1 from dict2 (or vice versa). It would thus be something like this:
dict_difference = {'hi' : 5 , 'thanks' : -12, 'please' : 10}
I know that subtracting one dictionary from another by :
dict1 = Counter({'hi' = 45, 'thanks' = 34, 'please' = 60})
dict2 = Counter({'hi' = 40, 'thanks' = 46, 'please' = 50})
dict3 = dict1-dict2
# will only return the positive values so it will give:
dict3 = {'hi'= 5, 'please' = 10}
# which is NOT what I want.
I also thought of converting the dictionaries into a list of pairs (I think this is how it is called) :
dictlist = []
for key, value in dict1.iteritems():`
temp = (key, value)
dictlist.append(temp)
and therefore
print dictlist #gives:
[('hi', 45),('thanks' = 34), ('please' = 60)]
So I thought that if I can manage to convert the dictionary into the list of pairs and then to make it in the form of the key:value to be key = value I would be able to apply the subtract() method and achieve what I want.
I thought of achieving it through the def __repr__(self)
as shown in https://docs.python.org/2/library/collections.html but I didn't get far.
I would be most grateful for any help. Please, if possible leave description for your code. If my approach is wrong and there is an easier way of subtracting the values of one dictionary from another please share it as well.