find non-empty value in a dictionary

Peter Hansen peter at engcorp.com
Tue Apr 15 22:42:37 EDT 2003


matthew wrote:
> 
> say you have a dictionay d =
> {'X': 0.0, 'Y'': 240.2, 'Z': 0.0, 'P': 13.3445}
> 
> where p divides pretty much evenly into Y; in this case approx 18
> 
> P will always be present and only one of X,Y,Z will have a non-zero value.
> 
> How can I easily find which X,Y, or Z is non-zero; esp. given that
> comparing floats is 'inaccurate' as in:
> 
> if X != 0:
>         <stuff>

I don't really understand half of what you're asking, but in this
particular case you might not need to be so concerned.  

While comparing floats is "inaccurate" in one sense, comparing one
float zero against another will always return True, provided you 
haven't arrived at these values by *numerical calculation*.  In
other words, if these values are actually read in from some data
file or something, and they originally started out as, say, 
strings containing "0.0", then you can definitely compare them
with 0.0 without problem.

If they are only *nearly* zero, as a result of some calculation,
then you're quite right in avoiding the direct comparison.

-Peter




More information about the Python-list mailing list