'How to eliminate division by 0 error when using dictionaries?

I'm adding constraints to an optimization model, and my parameters are stored in data dictionaries. I'm receiving a division by 0 error since the denominator is the product of values in two dictionaries and either one of the values could be zero. Either 'mydict_phite' or 'mydict_weight' could have a value of 0. How do I add an exception?

objvaluetimenode = {}
for t in timep: #ERROR
    for k,i,g in dnode:
        objvaluetimenode[k,i,g,t] = (mydict_weightn[(k, i,g)] * (mydict_phite[(k, i,g)] - solutiondnode[k, i, g,t]))/ ( mydict_weightn[(k,i,g)] * mydict_phite[(k, i,g)])

Here's the error I'm receiving:

<ipython-input-88-701319efb8bf> in RL(whyno, Zedno)
    454     for t in timep: #ERROR
    455         for k,i,g in dnode:
--> 456             objvaluetimenode[k,i,g,t] = (mydict_weightn[(k, i,g)] * (mydict_phite[(k, i,g)] - solutiondnode[k, i, g,t]))/ ( mydict_weightn[(k,i,g)] * mydict_phite[(k, i,g)])
    457 
    458 

ZeroDivisionError: float division by zero


Solution 1:[1]

You can try and catch the exception. If this specific exception occurs, assign the value of 0:

objvaluetimenode = {}
for t in timep: #ERROR
    for k,i,g in dnode:
        try:
            objvaluetimenode[k,i,g,t] = (mydict_weightn[(k, i,g)] * (mydict_phite[(k, i,g)] - solutiondnode[k, i, g,t]))/ ( mydict_weightn[(k,i,g)] * mydict_phite[(k, i,g)])
        except ZeroDivisionError:
            objvaluetimenode[k,i,g,t] = 0

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 JarroVGIT