Program to invert a Dictionary

Python Program to invert a Dictionary

In the previous article, we have discussed Python Program to Check if two Lines are Parallel or Not
Dictionary in python:

Python includes a class dictionary, which is typically defined as a set of key-value pairs. In Python, inverting a dictionary means swapping the key and value in the dictionary.

One thing is certain: complexity can be found in all of the different ways of storing key-value pairs. That is why dictionaries are used.

Python dictionaries are mutable collections of things that contain key-value pairs. The dictionary contains two main components: keys and values. These keys must be single elements, and the values can be of any data type, such as list, string, integer, tuple, and so on. The keys are linked to their corresponding values. In other words, the values can be retrieved using their corresponding keys.

A dictionary is created in Python by enclosing numerous key-value pairs in curly braces.

For example :

dictionary ={‘monday’:1, ‘tuesday’:2, ‘wednesday’:3}

The output after inverting the dictionary is { 1: [‘monday’] , 2: [‘tuesday’] , 3: [‘wednesday’] }

Given a dictionary, and the task is to invert the given dictionary.

Examples:

Example1:

Input:

Given dictionary = {10: 'jan', 20: 'feb', 30: 'march', 40: 'April', 50: 'may'}

Output:

The inverse of the given dictionary =  {'jan': [10], 'feb': [20], 'march': [30], 'April': [40], 'may': [50]}

Example 2:

Input:

Given dictionary = {'monday': 1, 'tuesday': 2, 'wednesday': 3}

Output:

The inverse of the given dictionary = {1: ['monday'], 2: ['tuesday'], 3: ['wednesday']}

Program to invert a Dictionary in Python

Below are the ways to invert a given dictionary

Method #1: Using For Loop (Static Input)

Approach:

  • Give the dictionary as static input and store it in a variable.
  • Create a new empty dictionary say ” inverse_dict” and store it in another variable.
  • Iterate in the above dictionary using the dictionary. items() and for loop.
  • Check if the value is present in the above declared  ” inverse_dict” using the if conditional statement and the ‘in’ keyword.
  • If the statement is true, then append the value to the “inverse_dict” dictionary using the append() function.
  • Else assign the value to the key.
  • Print the above declared ” inverse_dict” variable to get the inverse of the given dictionary.
  • The Exit of the program.

Below is the implementation:

# Give the dictionary as static input and store it in a variable.
gvn_dict = {'monday': 1, 'tuesday': 2, 'wednesday': 3}
# Create a new empty dictionary say " inverse_dict" and store it in another variable.
inverse_dict = {}
# Iterate in the above dictionary using the dictionary. items() and for loop.
for key, value in gvn_dict.items():
  # Check if the value is present in the above declared  " inverse_dict" using
  # the if conditional statement and the 'in' keyword.
    if value in inverse_dict:
     # If the statement is true, then append the value to the "inverse_dict" dictionary
     # using the append() function.
        inverse_dict[value].append(key)
    else:
     # Else assign the value to the key.
        inverse_dict[value] = [key]
  # Print the above declared " inverse_dict" variable to get the inverse of the
  # given dictionary.
print("The inverse of the given dictionary = ", inverse_dict)

Output:

The inverse of the given dictionary =  {1: ['monday'], 2: ['tuesday'], 3: ['wednesday']}

Method #2: Using For Loop (User Input)

Approach:

  • Take a dictionary and initialize it with an empty dictionary using dict() or {}.
  • Give the number of keys as user input using int(input()) and store it in a variable.
  • Loop till the given number of keys using for loop.
  • Inside the for loop scan the key and value as user input using input(), split() functions, and store them in two separate variables.
  • Initialize the key with the value of the dictionary.
  • Create a new empty dictionary say ” inverse_dict” and store it in another variable.
  • Iterate in the above dictionary using the dictionary. items() and for loop.
  • Check if the value is present in the above declared  ” inverse_dict” using the if conditional statement and the ‘in’ keyword.
  • If the statement is true, then append the value to the “inverse_dict” dictionary using the append() function.
  • Else assign the value to the key.
  • Print the above declared ” inverse_dict” variable to get the inverse of the given dictionary.
  • The Exit of the program.

Below is the implementation:

# Take a dictionary and initialize it with an empty dictionary using dict() or {}.
gvn_dict = {}
# Give the number of keys as user input using int(input()) and store it in a variable.
numb_of_kys = int(
    input('Enter some random number of keys of the dictionary = '))
# Loop till the given number of keys using for loop.
for p in range(numb_of_kys):
        # Inside the for loop scan the key and value as
    # user input using input(),split() functions
    # and store them in two separate variables.
    keyy, valuee = input(
        'Enter key and value separated by spaces = ').split()
    # Initialize the key with the value of the dictionary.
    gvn_dict[keyy] = valuee

# Create a new empty dictionary say " inverse_dict" and store it in another variable.
inverse_dict = {}
# Iterate in the above dictionary using the dictionary. items() and for loop.
for key, value in gvn_dict.items():
  # Check if the value is present in the above declared  " inverse_dict" using
  # the if conditional statement and the 'in' keyword.
    if value in inverse_dict:
     # If the statement is true, then append the value to the "inverse_dict" dictionary
     # using the append() function.
        inverse_dict[value].append(key)
    else:
     # Else assign the value to the key.
        inverse_dict[value] = [key]
  # Print the above declared " inverse_dict" variable to get the inverse of the
  # given dictionary.
print("The inverse of the given dictionary = ", inverse_dict)

Output:

Enter some random number of keys of the dictionary = 5
Enter key and value separated by spaces = hello 785
Enter key and value separated by spaces = this 100
Enter key and value separated by spaces = is 900
Enter key and value separated by spaces = btechgeeks 500
Enter key and value separated by spaces = python 400
The inverse of the given dictionary = {'785': ['hello'], '100': ['this'], '900': ['is'], '500': ['btechgeeks'], '400': ['python']}

Explore more instances related to python concepts from Python Programming Examples Guide and get promoted from beginner to professional programmer level in Python Programming Language.