find non-empty value in a dictionary
Dylan Reinhardt
python at dylanreinhardt.com
Tue Apr 15 22:10:31 EDT 2003
What about:
if x:
<stuff>
elif y:
<stuff>
Etc, etc.
Seems to work fine with a float value of 0. There may be some edge case
where this doesn't work, but if there is, I haven't found it.
If you're just looking for the result (not which variable had the
non-zero value), you could do something like (untested):
result = max([d[var] / d['P'] for var in ['X','Y','Z']])
HTH,
Dylan
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.
>
> 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>
> 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?
>
> any hints on best practice with comparing floats.
>
> Thanks. matthew.
>
>
More information about the Python-list
mailing list