Rounding off Values of dicts (in a list) to 2 decimal points
Peter Otten
__peter__ at web.de
Thu Oct 3 13:41:36 EDT 2013
tripsvt at gmail.com wrote:
> On Wednesday, October 2, 2013 10:01:16 AM UTC-7, tri... 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:
>>
>>
>>
>>
>>
>> def roundingVals_toTwoDeci():
>>
>> global y
>>
>> for d in y:
>>
>> for k, v in d.items():
>>
>> v = ceil(v*100)/100.0
>>
>> return
>>
>> roundingVals_toTwoDeci()
>>
>>
>>
>>
>>
>>
>>
>> But it is not working - I am still getting the old values.
> ____________________________________
>
> I am not sure what's going on but here's the current scenario: I get the
> values with 2 decimal places as I originally required. When I do
> json.dumps(), it works fine. The goal is to send them to a URL and so I do
> a urlencode. When I decode the urlencoded string, it gives me the same
> goodold 2 decimal places. But, for some reason, at the URL, when I check,
> it no longer limits the values to 2 decimal places, but shows values like
> 9.10003677694312. What's going on. Here's the code that I have:
>
> class LessPrecise(float):
> def __repr__(self):
> return str(self)
>
> def roundingVals_toTwoDeci(y):
> for d in y:
> for k, v in d.iteritems():
> d[k] = LessPrecise(round(v, 2))
> return
That should only process the first dict in the list, due to a misplaced
return.
> roundingVals_toTwoDeci(y)
> j = json.dumps(y)
> print j
>
> //At this point, print j gives me
>
> [{"a": 80.0, "b": 0.0, "c": 10.0, "d": 10.0}, {"a": 100.0, "b": 0.0, "c":
> [{0.0, "d": 0.0}, {"a":
> 80.0, "b": 0.0, "c": 10.0, "d": 10.0}, {"a": 90.0, "b": 0.0, "c": 0.0,
> "d": 10.0}]
>
> //then I do,
> params = urllib.urlencode({'thekey': j})
>
> //I then decode params and print it and it gives me
>
> thekey=[{"a": 80.0, "b": 0.0, "c": 10.0, "d": 10.0}, {"a": 100.0, "b":
> 0.0, "c": 0.0, "d": 0.0}, {"a": 80.0, "b": 0.0, "c": 10.0, "d": 10.0},
> {"a": 90.0, "b": 0.0, "c": 0.0, "d": 10.0}]
>
> However, at the URL, the values show up as 90.000043278694123
Can you give the actual code, including the decoding part? Preferably you'd
put both encoding and decoding into one small self-contained demo script.
More information about the Python-list
mailing list