find non-empty value in a dictionary

Chad Netzer cnetzer at
Wed Apr 16 04:14:21 CEST 2003

On Tue, 2003-04-15 at 18:26, matthew wrote:
> hi,
> 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.

Hmmm, sounds homework-ish, but I'll byte...

> How can I easily find which X,Y, or Z is non-zero;

Well, if you can guarantee the 0.0 floating point values are exactly 0.0
(because you initialize them to 0.0, for example), then using direct
comparison is fine.

>  esp. given that 
> comparing floats is 'inaccurate' as in:

It is perfectly accurate.  It is just that floats can differ by very
small amounts, and comparision compares it they are EXACTLY equal.  If
you initialize to a specific value, you can do an exact comparision.

> if X != 0:
> 	<stuff>
> elif Y != 0:
> 	<stuff>
> elif Z != 0:
> 	<stuff>
> else:
> 	<stuff-up>
> Also, once the correct axis is found,  exactly the same maths will be 
> applied which means that in the above, the same statement will be 
> replicated excepting the axis variable. any ideas on the best pythonic 
> way to tackle this?

When you are repeating chunks of code, time to make a function. 
Presumably it will take an argument that represents the value of the
"axis variable", and return a result.

> any hints on best practice with comparing floats.

Well, comparing them works fine.  Floats can be large than, less than,
or equal to each other (basically).  The trick is that when people say
they want to know when a float is "equal" to zero, due to some
calculation, they often mean that they want to know when it is very
close to zero (since a calculation may return a very small result that
is not zero).

At that point, you have to decide how close is close enough to mean

A common technique is to subtract the floats, and see if their
difference is less than some "tolerance" value. ie:

tol = 0.0000001   # this value is 1e-7

a = 0.000000000001  # A small value (1e-12)

if abs(0.0 - a) < tol:
    print "The value %s is very close to 0." % repr(a)

You can built a function to compare whether any two floats are
approximately equal:

def equal_floats(a, b, tol=1e-7):
    return abs(a-b) < tol

Knuth goes even further to allow defining tolerance as a proportion of
the largest of a or b (see Seminumerical Algorithms text)

Any further questions about floats, doubles, etc. may be answered by
Google search on "floating point FAQ".


Chad Netzer
(any opinion expressed is my own and not NASA's or my employer's)

More information about the Python-list mailing list