Rounding off Values of dicts (in a list) to 2 decimal points

Neil Cerutti neilc at norwich.edu
Wed Oct 2 13:32:14 EDT 2013


On 2013-10-02, tripsvt at gmail.com <tripsvt at gmail.com> wrote:
>  am trying to round off values in a dict to 2 decimal points
>  but have been unsuccessful so far. The input I have is like
>  this:
>
>     y = [{'a': 80.0, 'b': 0.0786235, 'c': 10.0, 'd': 10.6742903}, {'a': 80.73246, 'b': 0.0, 'c': 10.780323, 'd': 10.0}, {'a': 80.7239, 'b': 0.7823640, 'c': 10.0, 'd': 10.0}, {'a': 80.7802313217234, 'b': 0.0, 'c': 10.0, 'd': 10.9762304}]
>
> I want to round off all the values to two decimal points using
> the ceil function. Here's what I have:

I recommend using the builtin function round instead of
math.ceil. math.ceil doesn't do what is normally thought of as
rounding. In addition, it supports rounding to different numbers
of decimal places.

>     def roundingVals_toTwoDeci():
>         global y

You are hopefully* making modifications to y's object, but not rebinding y,
so you don't need this global statement.

>         for d in y:
>             for k, v in d.items():
>                 v = ceil(v*100)/100.0

[*] You're binding v to a new float object here, but not
modifying y. Thus, this code will have no effect on y.

You need to assign to y[k] here instead.

for k, v in d.items():
    y[k] = round(v, 2)

>         return

Bare returns are not usual at the end of Python functions. Just
let the function end; it returns None either way. Only return
when you've got an interesting value to return, or when you need
to end execution of the function early.

-- 
Neil Cerutti



More information about the Python-list mailing list