Python - Convert Dictionary values to Absolute Magnitude
Last Updated :
10 May, 2023
Given a dictionary, convert its values to absolute.
Input : test_dict = {"Gfg" : -5, "is" : -7, "Best" : -2}
Output : {"Gfg" : 5, "is" : 7, "Best" : 2}
Explanation : All negative elements changed to positive with same magnitude
Input : test_dict = {"Gfg" : -8, "is" : 7, "Best" : -2}
Output : {"Gfg" : 8, "is" : 7, "Best" : 2}
Explanation : All negative elements changed to positive with same magnitude
Method #1 : Using loop + abs()
This is one of the ways in which this task can be performed. In this, we iterate for each value of dictionary using loop and perform the absolute magnitude conversion using abs().
Python3
# Python3 code to demonstrate working of
# Convert Dictionary values to Absolute Magnitude
# Using loop + abs()
# initializing dictionary
test_dict = {"Gfg" : 5, "is" : -7, "Best" : 2, "for" : -9, "geeks" : -8}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# using abs() to perform conversion
# from negative to positive values
for ele in test_dict:
test_dict[ele] = abs(test_dict[ele])
# printing result
print("Dictionary after absolute conversion : " + str(test_dict))
OutputThe original dictionary is : {'Gfg': 5, 'is': -7, 'Best': 2, 'for': -9, 'geeks': -8}
Dictionary after absolute conversion : {'Gfg': 5, 'is': 7, 'Best': 2, 'for': 9, 'geeks': 8}
Time Complexity: O(n), where n is the values in dictionary
Auxiliary Space: O(n), where n is the size of dictionary
Method #2 : Using dictionary comprehension + abs()
This task is similar to above method. The difference being dictionary comprehension is used instead of loop to perform the task of iteration through keys.
Python3
# Python3 code to demonstrate working of
# Convert Dictionary values to Absolute Magnitude
# Using dictionary comprehension + abs()
# initializing dictionary
test_dict = {"Gfg": 5, "is": -7, "Best": 2, "for": -9, "geeks": -8}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# dictionary comprehension using to compile result
# items() used to extract dictionary keys and values.
res = {key: abs(val) for key, val in test_dict.items()}
# printing result
print("Dictionary after absolute conversion : " + str(res))
OutputThe original dictionary is : {'Gfg': 5, 'is': -7, 'Best': 2, 'for': -9, 'geeks': -8}
Dictionary after absolute conversion : {'Gfg': 5, 'is': 7, 'Best': 2, 'for': 9, 'geeks': 8}
Method #3 : Without using abs()
Python3
# Python3 code to demonstrate working of
# Convert Dictionary values to Absolute Magnitude
# initializing dictionary
test_dict = {"Gfg" : 5, "is" : -7, "Best" : 2, "for" : -9, "geeks" : -8}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
for ele in test_dict:
if(test_dict[ele]<0):
test_dict[ele]=-1*test_dict[ele]
# printing result
print("Dictionary after absolute conversion : " + str(test_dict))
OutputThe original dictionary is : {'Gfg': 5, 'is': -7, 'Best': 2, 'for': -9, 'geeks': -8}
Dictionary after absolute conversion : {'Gfg': 5, 'is': 7, 'Best': 2, 'for': 9, 'geeks': 8}
Method 4: using map() and abs() functions:
Python3
# Python3 code to demonstrate working of
# Convert Dictionary values to Absolute Magnitude
# Using map and abs
# initializing dictionary
test_dict = {"Gfg" : 5, "is" : -7, "Best" : 2, "for" : -9, "geeks" : -8}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# using map() and abs() to perform the absolute conversion
test_dict = dict(map(lambda x: (x[0], abs(x[1])), test_dict.items()))
# printing result
print("Dictionary after absolute conversion : " + str(test_dict))
OutputThe original dictionary is : {'Gfg': 5, 'is': -7, 'Best': 2, 'for': -9, 'geeks': -8}
Dictionary after absolute conversion : {'Gfg': 5, 'is': 7, 'Best': 2, 'for': 9, 'geeks': 8}
Time complexity: O(n), where n is the number of elements in the dictionary.
Auxiliary space: O(n), because we are creating a new dictionary to store the results of the absolute value conversion.
Method #5 : Using operator.abs() method
Approach
This is one of the ways in which this task can be performed.
- In this, we iterate for each value of dictionary using loop
- perform the absolute magnitude conversion using operator.abs()
Python3
# Python3 code to demonstrate working of
# Convert Dictionary values to Absolute Magnitude
# Using loop + operator.abs()
# initializing dictionary
test_dict = {"Gfg" : 5, "is" : -7, "Best" : 2, "for" : -9, "geeks" : -8}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# using operator.abs() to perform conversion
# from negative to positive values
import operator
for ele in test_dict:
test_dict[ele] = operator.abs(test_dict[ele])
# printing result
print("Dictionary after absolute conversion : " + str(test_dict))
OutputThe original dictionary is : {'Gfg': 5, 'is': -7, 'Best': 2, 'for': -9, 'geeks': -8}
Dictionary after absolute conversion : {'Gfg': 5, 'is': 7, 'Best': 2, 'for': 9, 'geeks': 8}
Time complexity: O(n), where n is the number of elements in the dictionary.
Auxiliary space: O(n), because we are creating a new dictionary to store the results of the absolute value conversion.
Method 6: Using numpy library
- Convert the dictionary values to absolute magnitude using the numpy abs() function and a dictionary comprehension
- Assign the resulting dictionary to the test_dict variable using test_dict = {key: np.abs(value) for key, value in test_dict.items()}.
- Print the resulting dictionary using print("Dictionary after absolute conversion : " + str(test_dict)).
Python3
# importing the numpy library
import numpy as np
# initializing dictionary
test_dict = {"Gfg" : 5, "is" : -7, "Best" : 2, "for" : -9, "geeks" : -8}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# converting dictionary values to absolute magnitude using numpy
test_dict = {key: np.abs(value) for key, value in test_dict.items()}
# printing result
print("Dictionary after absolute conversion : " + str(test_dict))
Output:
The original dictionary is : {'Gfg': 5, 'is': -7, 'Best': 2, 'for': -9, 'geeks': -8}
Dictionary after absolute conversion : {'Gfg': 5, 'is': 7, 'Best': 2, 'for': 9, 'geeks': 8}
Time complexity: O(n)
Auxiliary space: O(n), where n is the number of items in the dictionary.
Method 7 : Using pandas library
- Importing the pandas module using the "import" statement and giving it an alias "pd".
- Initializing a Python dictionary "test_dict" with keys and values.
- Printing the original dictionary using the "print()" function.
- Creating a pandas DataFrame "df" from the dictionary "test_dict" using the "pd.DataFrame.from_dict()" method, specifying the orientation of the
- dictionary as 'index', and providing the column name as 'values'.
- Applying the "abs()" function on the 'values' column of the pandas DataFrame to calculate absolute values.
- Converting the pandas DataFrame back to a Python dictionary "abs_dict" using the "to_dict()" method.
- Printing the final dictionary after absolute conversion using the "print()" function.
Python3
import pandas as pd
# initializing dictionary
test_dict = {"Gfg" : 5, "is" : -7, "Best" : 2, "for" : -9, "geeks" : -8}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# creating pandas DataFrame
df = pd.DataFrame.from_dict(test_dict, orient='index', columns=['values'])
# calculating absolute values using abs() function
df['values'] = df['values'].abs()
# converting DataFrame back to dictionary
abs_dict = df.to_dict()['values']
# printing result
print("Dictionary after absolute conversion : " + str(abs_dict))
OUTPUT :
The original dictionary is : {'Gfg': 5, 'is': -7, 'Best': 2, 'for': -9, 'geeks': -8}
Dictionary after absolute conversion : {'Gfg': 5, 'is': 7, 'Best': 2, 'for': 9, 'geeks': 8}
Time complexity: O(n)
Auxiliary space: O(n)
Similar Reads
Python | Type conversion in dictionary values The problem of conventional type conversion is quite common and can be easily done using the built-in converters of python libraries. But sometimes, we may require the same functionality in a more complex scenario vis. for keys of list of dictionaries. Let's discuss certain ways in which this can be
4 min read
Convert Dictionary values to Strings In Python, dictionaries store key-value pairs, where values can be of any data type. Sometimes, we need to convert all the values of a dictionary into strings. For example, given the dictionary {'a': 1, 'b': 2.5, 'c': True}, we might want to convert the values 1, 2.5, and True to their string repres
3 min read
Python - Dictionary Values Mean Given a dictionary, find the mean of all the values present. Input : test_dict = {"Gfg" : 4, "is" : 4, "Best" : 4, "for" : 4, "Geeks" : 4} Output : 4.0 Explanation : (4 + 4 + 4 + 4 + 4) / 4 = 4.0, hence mean. Input : test_dict = {"Gfg" : 5, "is" : 10, "Best" : 15} Output : 10.0 Explanation : Mean of
4 min read
Python | Type conversion of dictionary items The interconversion of data types is quite common, and we may have this problem while working with dictionaries as well. We might have a key and corresponding list with numeric alphabets, and we with to transform the whole dictionary to integers rather than string numerics. Let's discuss certain way
6 min read
Python - Dictionary Values Mapped Summation Given a dictionary with a values list, our task is to extract the sum of values, found using mappings. Input : test_dict = {4 : ['a', 'v', 'b', 'e'], 1 : ['g', 'f', 'g'], 3 : ['e', 'v']}, map_vals = {'a' : 3, 'g' : 8, 'f' : 10, 'b' : 4, 'e' : 7, 'v' : 2} Output : {4: 16, 1: 26, 3: 9} Explanation : "
6 min read