尝试在Python中对一个字典的值进行四舍五入处理

问题描述 投票:0回答:1
table_percentages = {'e': 42.857142857142854, 'g': 28.57142857142857, 'x': 14.285714285714285, 'c': 14.285714285714285}

试图将上面字典中的值四舍五入到小数点后两位。我尝试了下面的For Loop,但没有得到想要的输出。我只得到了一个单一的输出,即一个四舍五入的值。

rounded_percentages = {}
for key in table_percentages:
    rounded_percentages = round(table_percentages[key], 2)
print(rounded_percentages)
python dictionary rounding
1个回答
1
投票

用这个。

rounded_percentages = {}
for key in table_percentages.keys():
    rounded_percentages[key] = round(table_percentages[key], 2)
print(rounded_percentages)
© www.soinside.com 2019 - 2024. All rights reserved.