How to Convert Dictionary values to Absolute Magnitude using Python?


Dictionaries are data structures that can contain key and values of any data type. The values can be of integer type as well. In this article we are going to see How to Convert Dictionary values to Absolute Magnitude using Python which simply means if a value is in negative it will be converted to it’s absolute or positive value while positive values will remain as it is.

I/O Example

Input = {'a':1 , 'b' : -1}

Output = {'a':1 , 'b' : 1}

To do this conversion, there are lot of techniques however 1 function that will be used along with majority of them is the abs() function. It is in built and returns the absolute value of a number provided to it as input or it can be considered as a function that calculates the magnitude of a numeric value regardless of its sign.

The abs() function basically takes a single argument, which can be an integer, floating-point number, or a complex number. It returns the absolute value of the input argument. If the input is a real number (integer or float), the function returns its positive value. If the input is a complex number, the function returns its magnitude, which is the distance from the origin (0, 0) in the complex plane.

Method 1: Loop and update (Naïve method)

This method simply iterates over the entire dictionary and applies the abs() function on every value of it. The values are accessed and set using the keys.

Example

my_dict = {'x': -11, 'y': 7, 'e': -82, 't': 42, 'r': -175}
for key in my_dict:
    my_dict[key] = abs(my_dict[key])
print(my_dict)

Output

{'x': 11, 'y': 7, 'e': 82, 't': 42, 'r': 175}

Method 2: Dictionary Comprehension

Python's dictionary comprehension offers us with a straightforward method for quickly creating dictionaries with minimal syntax complexity. This construct generates new dictionaries by iterating over an iterable and assigning keys and values using intuitive expressions thereby improving readability while cutting explicit loops as well as extra lines of code.

Example

my_dict = {'x': -11, 'y': 7, 'e': -82, 't': 42, 'r': -175}

abs_dict = {key: abs(value) for key, value in my_dict.items()}
print(abs_dict)

Output

{'x': 11, 'y': 7, 'e': 82, 't': 42, 'r': 175}

Method 3: Using map() with lambda function

Python consists of a map() function which allows us to apply (or map) a given function to every element of an iterable and then returns an iterator consisting of the results. There 2 arguments it takes: the function to apply; the iterable to operate on.

In combination with lambda functions, which are anonymous functions defined on the fly, map() becomes a powerful tool for performing simple operations on elements of an iterable. Lambda functions are typically used when a function is needed for a short duration or as an argument to a higher-order function like map().

Example

my_dict = {'x': -11, 'y': 7, 'e': -82, 't': 42, 'r': -175}

abs_dict = {key: abs(value) for key, 
            value in map(lambda item: (item[0], item[1]), my_dict.items())}
print(abs_dict)

Output

{'x': 11, 'y': 7, 'e': 82, 't': 42, 'r': 175}

Method 4: Using dict() constructor and comprehension

Python's built-in dictionary constructor dict() can create new dictionary objects quickly and efficiently from various forms of input such as iterables, key-value pairs or even existing dictionaries.

Combines dictionary comprehension for easy dictionary creation using iterables or other data sources. With this flexible tool in hand, the dict() constructor becomes an efficient means of producing key-value mapping dictionaries with precise key/value pairs derived from iterables or other sources of data.

Example

my_dict = {'x': -11, 'y': 7, 'e': -82, 't': 42, 'r': -175}
abs_dict = dict((key, abs(value)) for key, value in my_dict.items())
print(abs_dict)

Output

{'x': 11, 'y': 7, 'e': 82, 't': 42, 'r': 175}

Method 5: Using a for loop and dictionary comprehension

The code provided below illustrates the creation of a dictionary named "my_dict" with multiple key-value pairs. Dictionary comprehension allows iterating over these keys to produce another dictionary called "abs_dict," where each key corresponds with an absolute value of its corresponding value in "my_dict," via abs() function. When run, abs_dict displays identically, yet with transformed absolute magnitude values instead. The code concludes by printing out this second version which still maintains identical keys but values have been transformed into their absolute magnitudes!

Example

my_dict = {'x': -11, 'y': 7, 'e': -82, 't': 42, 'r': -175}
abs_dict = {key: abs(my_dict[key]) for key in my_dict}
print(abs_dict)

Output

{'x': 11, 'y': 7, 'e': 82, 't': 42, 'r': 175}

Method 6: Using dictionary comprehension with the update() method

Dictionary comprehensions combined with an update function create an effective solution. After creating the dictionary named "my_dict", dictionary comprehension adds all its keys with their values updated accordingly to their absolute values.

Example

my_dict = {'x': -11, 'y': 7, 'e': -82, 't': 42, 'r': -175}
abs_dict = {}
abs_dict.update({key: abs(value) for key, value in my_dict.items()})
print(abs_dict)

Output

{'x': 11, 'y': 7, 'e': 82, 't': 42, 'r': 175}

Method 7: Using numpy

Python’s commonly used NumPy library offers us many functions. However in this case 1 such function which is of great use here is numpy.abs(). This allows us to calculate the absolute values of numerical elements inside of an array-like object. It takes input as an array or any scalar and then returns an array/scalar with absolute values of the corresponding elements.

Example

import numpy as np
my_dict = {'x': -11, 'y': 7, 'e': -82, 't': 42, 'r': -175}
abs_dict = {key: np.abs(value) for key, value in my_dict.items()}
print(abs_dict)

Output

{'x': 11, 'y': 7, 'e': 82, 't': 42, 'r': 175}

Method 8: Using pandas

Pandas is just another data handling and manipulation library like numpy. We create a pandas dataframe here from all the dictionary values and create a new column that we shall be calling as abs_values. We then apply the abs() function to the initial columns that contains the values. The new values i.e. after applying abs() are stored in the abs_values column and then converted back into a dictionary using the to_dict() function.

Example

import pandas as pd
my_dict = {'x': -11, 'y': 7, 'e': -82, 't': 42, 'r': -175}
df = pd.DataFrame({'values': my_dict})
# Apply the abs() function to the 'values' column.
df['abs_values'] = df['values'].abs()
abs_dict = df['abs_values'].to_dict()
print(abs_dict)

Output

{'e': 82, 'r': 175, 't': 42, 'x': 11, 'y': 7}

Conclusion

There are multiple ways in python to convert dictionary values to absolute magnitude. Majority of them make use of a function abs(). The methods include using loop, dictionary comprehension, map and lambda, dict constructor, loops with dictionary comprehension, dictionary comprehension with update(), numpy library and lastly the pandas library.

There are a total of 8 methods demonstrated and majority of them have the same time complexity of O(N) where N is indicative of the number of key-value pairs or the size of the dictionary values being processed.

Updated on: 29-Aug-2023

71 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements