Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Round off floating point values in dict

I am struggling to round off floating values in dictionary. To generate the dictionary I have used:

[{i: x.count(i)/float(len(x)) for i in x} for x in l]

My dictionary is:

P = [{'A': 0.700000000, 'B': 0.255555555}, {'B': 0.55555555, 'C': 0.55555555}, {'A': 0.255555555, 'B': 0.210000000, 'C': 0.2400000000}]

I need:

P = [{'A': 0.70, 'B': 0.25}, {'B': 0.55, 'C': 0.55}, {'A': 0.25, 'B': 0.21, 'C': 0.24}]
like image 380
Explore_SDN Avatar asked Sep 07 '15 08:09

Explore_SDN


1 Answers

This is a fairly simple way to do it. However, .7000 will become just .7

Rounding

for dict_value in P:
        for k, v in dict_value.items():
            dict_value[k] = round(v, 2)

[{'A': 0.7, 'B': 0.26}, {'C': 0.56, 'B': 0.56}, {'A': 0.26, 'C': 0.24, 'B': 0.21}]

Truncating

for dict_value in P:
    for k, v in dict_value.items():
        dict_value[k] = float(str(v)[:4])
[{'A': 0.7, 'B': 0.25}, {'C': 0.55, 'B': 0.55}, {'A': 0.25, 'C': 0.24, 'B': 0.21}]

The conversion to string chops off the extra 0's in 0.700000 and that is why it still shows as 0.7 instead of 0.70.

like image 86
Jared Mackey Avatar answered Oct 26 '22 21:10

Jared Mackey