Open In App

Python – Convert Dictionary values to Absolute Magnitude

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

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


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


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}

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


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}

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


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


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



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

Similar Reads