I have two Python dictionaries containing broadly the same keys and I am trying to multiply the values of each key pair. One dictionary is slightly larger (due to containing additional keys that I want to ignore). The problem I am having is that in some instances zeros in the denominator is causing ZeroDivisionError: division by zero
- my question therefore is, how can i amend my script so that I perform the division, accepting that when zero is in the denominator the result will be '0'?
dict1 = {'A':1,'B':1,'C':2,'D':0}
dict2 = {'A':2,'B':2,'C':4,'D':0,'E':5}
myfunc = {k : v / dict2[k] for k, v in dict1.items() if k in dict2}
Try the below (the idea is to make sure that the denominator is not zero before we divide)
dict1 = {'A': 1, 'B': 1, 'C': 2, 'D': 0}
dict2 = {'A': 2, 'B': 2, 'C': 4, 'D': 0, 'E': 5}
myfunc = {k: v / dict2[k] if dict2[k] else 0 for k, v in dict1.items() if k in dict2}
print(myfunc)
output
{'A': 0.5, 'B': 0.5, 'C': 0.5, 'D': 0}