Allow Division by Zero with Python Dicts

178 views Asked by At

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}
2

There are 2 answers

0
balderman On BEST ANSWER

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}
1
thethiny On
myfunc = {k : (v / dict2[k] if dict2[k] else 0) for k, v in dict1.items() if k in dict2}