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}]
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With