Open In App

Python – Round Off Dictionary Values to K decimals

Last Updated : 16 May, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given Dictionary with float values perform round off to K of all the values.

Input : {“Gfg” : 54.684034, “is” : 76.324334, “Best” : 28.43524}, K = 2 
Output : {“Gfg” : 54.68, “is” : 76.32, “Best” : 28.43} 
Explanation : Values rounded till 2. 

Input : {“Gfg” : 54.684034, “is” : 76.324334, “Best” : 28.43524}, K = 1 
Output : {“Gfg” : 54.6, “is” : 76.3, “Best” : 28.4} 
Explanation : Values rounded till 1.

Method #1 : Using loop + round()

This is one of the ways in which this task can be performed. In this, we iterate for all the values, and perform round off to nearest K values using round().

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))


Output

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}

Method #2 : Using dictionary comprehension + round()

This is yet another way in which this task can be performed. In this we performed similar task using above functionality, the difference being usage of dictionary comprehension to provide one-line solution.

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))


Output

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}

Method #3: Using float

This approach takes a dictionary and a value k as input, and returns a new dictionary with the values rounded to k decimal places.

  • Iterate through the items in the input dictionary
  • Round each value to k decimal places using f-string formatting.
  • Store the rounded value in a new dictionary with the same key.
  • Return the new dictionary with rounded values.

Python3




def round_dict_values(d, k):
    return {key: float(f"{value:.{k}f}") for key, value in d.items()}
d = {"Gfg" : 54.684034, "is" : 76.324334, "Best" : 28.43524}
k=3
print(round_dict_values(d, k))


Output

{'Gfg': 54.684, 'is': 76.324, 'Best': 28.435}

Time complexity: O(n), where n is the number of items in the input dictionary. The function needs to iterate through all the items in the dictionary once, and rounding each value takes constant time.

Space complexity: O(n), where n is the number of items in the input dictionary. The function needs to create a new dictionary with the same number of items as the input dictionary. The space required for rounding each value is negligible.

Approach#4:Using numpy:

Step-by-step approach:

  • Import numpy module.
  • Initialize the dictionary to be rounded off.
  • Initialize the number of decimals to round off to.
  • Convert the dictionary to a numpy array using np.array().\
  • Round off the values in the numpy array using np.round().
  • Create a new dictionary with rounded off values using a dictionary comprehension that iterates over the
  • original dictionary and the rounded off numpy array.
  • Print the result.

Python3




import numpy as np
 
# 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
 
# converting dictionary to numpy array
arr = np.array(list(test_dict.values()))
 
# rounding off the values in the array
rounded_arr = np.round(arr, K)
 
# creating a new dictionary with rounded off values
res = {key : rounded_arr[idx] for idx, key in enumerate(test_dict)}
 
# printing result
print("Values after round off : " + str(res))
#This code is contributed by Rayudu.


Output:
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}

Time complexity: O(n), where n is the number of elements in the dictionary.
Auxiliary Space: O(n), where n is the number of elements in the dictionary.

Approach #5: Using pandas library

Step-by-Step approach:

  • Import pandas library
  • Create a pandas Series from the given dictionary
  • Use the round() function to round off the values in the Series
  • Create a new dictionary with the rounded off values using the to_dict() method of the Series

Python3




# importing pandas library
import pandas as pd
 
# 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
 
# creating pandas series from the dictionary
s = pd.Series(test_dict)
 
# rounding off the values in the series
rounded_s = s.round(K)
 
# creating a new dictionary with rounded off values
res = rounded_s.to_dict()
 
# printing result
print("Values after round off : " + str(res))


Output: 

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}

Time complexity: O(n), where n is the number of elements in the dictionary
Auxiliary space: O(n), where n is the number of elements in the dictionary 



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads