Python – Inverse Dictionary Values List

PythonServer Side ProgrammingProgramming

When it is required to inverse the dictionary values to a list, a simple iteration and ‘append’ method is used.

Below is a demonstration of the same −

from collections import defaultdict
my_dict = {13: [12, 23], 22: [31], 34: [21], 44: [52, 31]}
print("The dictionary is :")
print(my_dict)
my_result = defaultdict(list)
for keys, values in my_dict.items():
   for val in values:
      my_result[val].append(keys)
print("The result is :")
print(dict(my_result))

Output

The dictionary is :
{34: [21], 44: [52, 31], 13: [12, 23], 22: [31]}
The result is :
{52: [44], 31: [44, 22], 12: [13], 21: [34], 23: [13]}

Explanation

  • The required packages are imported into the environment.

  • A dictionary is defined and displayed on the console.

  • An empty dictionary is created with defaultdict.

  • The elements of the dictionary are accessed and iterated over.

  • The values are appended to the empty dictionary using ‘append’ method.

  • This is the output that is displayed on the console.

raja
Published on 07-Sep-2021 09:29:44
Advertisements