Python - Round Off Dictionary Values to K decimals
Last Updated :
16 May, 2023
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))
OutputThe 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))
OutputThe 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
Similar Reads
How to Round Floating Value to Two Decimals in Python In this article, we will round off a float value in Python to the nearest two decimal places. Python provides us with multiple approaches to format numbers to 2 decimal places.Using round() round() function is the most efficient way to round a number to a specified number of decimal places. It direc
2 min read
Python Update Dictionary Value by Key A Dictionary in Python is an unordered collection of key-value pairs. Each key must be unique, and you can use various data types for both keys and values. Dictionaries are enclosed in curly braces {}, and the key-value pairs are separated by colons. Python dictionaries are mutable, meaning you can
3 min read
Python - Decrement Dictionary value by K Sometimes, while working with dictionaries, we can have a use-case in which we require to decrement a particular keyâs value by K in dictionary. It may seem a quite straight forward problem, but catch comes when the existence of a key is not known, hence becomes a 2 step process at times. Letâs disc
3 min read
Python - Rotate dictionary by K Given a dictionary perform its reordering by right rotating dictionary keys by K. Examples: Input : test_dict = {1:6, 8:1, 9:3, 10:8, 12:6, 4:9}, K = 2 Output : {12: 6, 4: 9, 1: 6, 8: 1, 9: 3, 10: 8} Explanation : After right rotation ( cyclic ) by 2 elements, items are re-arranged. Input : test_dic
4 min read
Python - Dictionary Tuple Values Update The task of updating tuple values in a dictionary involves modifying each tuple in the dictionary by applying a specific operation to its elements. In this case, the goal is to update each element of the tuple based on a given condition, such as multiplying each element by a constant. For example, g
3 min read