user6053895
user6053895

Reputation:

Rounding a dictionary floating point value to 2 decimal point: Python

I have the following dictionary values and I would like to round it to two decimal points. But I couldn't find a convenient solution for this.

my_dict= {180: 0.40111111111111114, 190: 0.28571428571428575, 200: 0.28451612903225804, 210: 0.2304761904761905, 220: 0.1977570093457944, 230: 0.17587786259541985, 240: 0.16025641025641027}

I have tried many possibilities with round method but didn't work.

For example: round(my_dict, 2) or print(f'{my_dict:.2f}')

But couldn't get the whole value rounded.

Is there any way to do this?

Upvotes: 2

Views: 3400

Answers (3)

Parthesh Soni
Parthesh Soni

Reputation: 143

Referring this answer, a nice one-liner would be:

my_dict.update((key, round(val, 2)) for key, val in my_dict.items()) 

Upvotes: 0

Lucan
Lucan

Reputation: 3655

You can use dictionary comprehension like so

my_dict = {180: 0.40111111111111114, 190: 0.28571428571428575, 200: 0.28451612903225804, 210: 0.2304761904761905, 220: 0.1977570093457944, 230: 0.17587786259541985, 240: 0.16025641025641027}

my_dictionary = {k: round(v, 2) for k, v in my_dict.items()}

print(my_dictionary)

Prints

{180: 0.4, 190: 0.29, 200: 0.28, 210: 0.23, 220: 0.2, 230: 0.18, 240: 0.16}

Upvotes: 2

Parth Shah
Parth Shah

Reputation: 1485

This method is the easiest to understand. Iterate through the dictionary and create a new dictionary with the same key, rounded value. More info here.

my_dict_rounded = dict()
for key, value in my_dict.items():
    my_dict_rounded[key] = round(value, 2)

# my_dict_rounded = {180: 0.4, 190: 0.29, 200: 0.28, 210: 0.23, 220: 0.2, 230: 0.18, 240: 0.16}

Upvotes: 0

Related Questions