4

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.

HR123r
  • 181
  • 2
  • 10

2 Answers2

10

First, the format of your dictionaries is not correct (: and not =):

dict1 = {'hi':45, 'thanks':34, 'please':60}
dict2 = {'hi':40, 'thanks':46, 'please':50}

You can use a dictionary comprehension. You basically loop through one dictionary, check that the key is also in the second dictionary and insert the difference of the values in the output dictionary. All in one line.

dic = {key: dict1[key]-dict2[key] for key in dict1 if key in dict2}
Julien Spronck
  • 15,069
  • 4
  • 47
  • 55
  • Hi! Thank you very much for your reply and for solving this for me as well as correcting me on the dictionary syntax. I tried it out and indeed it works! Thanks! – HR123r Mar 25 '15 at 22:34
3

You were on the right path with thinking about using the dictionarys' keys.

Here, I go through the first dictionary's keys, checking if they're in dictionary2. Then I do the same with dictionary2, checking for keys in dictionary1, but also ensuring that the key isn't already in the result dictionary so we don't do duplicate subtraction.

dict1 = {'hi': 45, 'thanks': 34, 'please': 60}
dict2 = {'hi': 40, 'thanks': 46, 'please': 50}
result = {}

for key in dict1.keys():
    if key in dict2:
    result[key] = dict1[key] - dict2[key]

for key in dict2.keys():
    if key in dict1 and not key in result:
    result[key] = dict1[key] - dict2[key]
Celeo
  • 5,583
  • 8
  • 39
  • 41
  • If the goal is to only process keys shared by both dicts, then the second loop is unnecessary, since the first loop already found all shared keys. Also, the call to `keys` is unnecessary, since looping over a dict loops over the keys already. Calling `keys` just spends unnecessary time and space building a list of keys. – user2357112 Mar 25 '15 at 21:32
  • Was about to say the same thing. – Julien Spronck Mar 25 '15 at 21:33
  • @JulienSpronck's code is actually more efficient than this paste, so go with his. – Celeo Mar 25 '15 at 22:36