📜  Python – 将字典值四舍五入为 K 小数

📅  最后修改于: 2022-05-13 01:55:15.535000             🧑  作者: Mango

Python – 将字典值四舍五入为 K 小数

给定具有浮点值的字典对所有值执行四舍五入到 K。

方法#1:使用循环+round()

这是可以执行此任务的方式之一。在此,我们迭代所有值,并使用 round() 执行舍入到最接近的 K 值。

Python3
# Python3 code to demonstrate working of 
# Round Off Dictionary Values to K decimals
# Using loop + round()
  
# initializing dictionary
test_dict = {"Gfg" : 54.684034, "is" : 76.324334, "Best" : 28.43524}
  
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
  
# initializing K 
K = 3
  
# loop to iterate for values 
res = dict()
for key in test_dict:
      
    # rounding to K using round()
    res[key] = round(test_dict[key], K)
  
# printing result 
print("Values after round off : " + str(res))


Python3
# Python3 code to demonstrate working of 
# Round Off Dictionary Values to K decimals
# Using dictionary comprehension + round()
  
# initializing dictionary
test_dict = {"Gfg" : 54.684034, "is" : 76.324334, "Best" : 28.43524}
  
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
  
# initializing K 
K = 3
  
# Encapsulating solution using single comprehension
res = {key : round(test_dict[key], K) for key in test_dict}
  
# printing result 
print("Values after round off : " + str(res))


输出
The original dictionary is : {'Gfg': 54.684034, 'is': 76.324334, 'Best': 28.43524}
Values after round off : {'Gfg': 54.684, 'is': 76.324, 'Best': 28.435}

方法 #2:使用字典理解 + round()

这是可以执行此任务的另一种方式。在此,我们使用上述功能执行了类似的任务,不同之处在于使用字典理解来提供单行解决方案。

Python3

# Python3 code to demonstrate working of 
# Round Off Dictionary Values to K decimals
# Using dictionary comprehension + round()
  
# initializing dictionary
test_dict = {"Gfg" : 54.684034, "is" : 76.324334, "Best" : 28.43524}
  
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
  
# initializing K 
K = 3
  
# Encapsulating solution using single comprehension
res = {key : round(test_dict[key], K) for key in test_dict}
  
# printing result 
print("Values after round off : " + str(res)) 
输出
The original dictionary is : {'Gfg': 54.684034, 'is': 76.324334, 'Best': 28.43524}
Values after round off : {'Gfg': 54.684, 'is': 76.324, 'Best': 28.435}