Davide Di Menna - 18 days ago 7
Python Question

# Divide two dictionaries of float values with zero values

i have a problem with division error.. I use two dictionarie and i have to divide them by other dict.. But some values are 0.. I don't want an error but i want

My two dict:

probspam:

``````  {0: [3.75199226626618e-79], 1: [1.0384638247478166e-25], 2: [3.876104531640006e-157]}
``````

probham:

`````` {0: [1.0143598477460146e-78], 1: [0.0], 2: [2.2740883119510355e-138]}
``````

the wrong function:

``````def bayes (probspam, probham):
try:
lista={k: [probspam[k][0]/probham[k][0]] for k in probham}
except ZeroDivisionError:
k=0
return lista
``````

how can i tell my system that when
`probham[k]=0`
, it should assign 0 to the result of the division and not give me:"ZeroDivisionError: float division by zero"?

Answer

Does it what you are looking for?

``````def bayes (probspam, probham):
lista={k: [probspam[k][0]/probham[k][0] if probham[k][0] !=0 else .0] for k in probham}
return lista
``````

or, if you need a 0.0 instead of [0.0] as a value

``````def bayes (probspam, probham):
lista={k: [probspam[k][0]/probham[k][0]] if probham[k][0] !=0 else .0 for k in probham}
return lista
``````

List/dict comprehensions is powerful! :)

Comments