{"id":16833,"date":"2021-08-17T08:51:15","date_gmt":"2021-08-17T03:21:15","guid":{"rendered":"https:\/\/python-programs.com\/?p=16833"},"modified":"2021-11-22T18:37:21","modified_gmt":"2021-11-22T13:07:21","slug":"python-program-to-invert-a-dictionary","status":"publish","type":"post","link":"https:\/\/python-programs.com\/python-program-to-invert-a-dictionary\/","title":{"rendered":"Python Program to invert a Dictionary"},"content":{"rendered":"

In the previous article, we have discussed Python Program to Check if two Lines are Parallel or Not<\/a>
\nDictionary in python:<\/strong><\/p>\n

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.<\/p>\n

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.<\/p>\n

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.<\/p>\n

A dictionary is created in Python by enclosing numerous key-value pairs in curly braces.<\/p>\n

For example :<\/strong><\/p>\n

dictionary ={‘monday’:1, ‘tuesday’:2, ‘wednesday’:3}<\/p>\n

The output after inverting the dictionary is { 1: [‘monday’] , 2: [‘tuesday’] , 3: [‘wednesday’] }<\/p>\n

Given a dictionary, and the task is to invert the given dictionary.<\/p>\n

Examples:<\/strong><\/p>\n

Example1:<\/strong><\/p>\n

Input:<\/strong><\/p>\n

Given dictionary = {10: 'jan', 20: 'feb', 30: 'march', 40: 'April', 50: 'may'}<\/pre>\n

Output:<\/strong><\/p>\n

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

Example 2:<\/strong><\/p>\n

Input:<\/strong><\/p>\n

Given dictionary = {'monday': 1, 'tuesday': 2, 'wednesday': 3}<\/pre>\n

Output:<\/strong><\/p>\n

The inverse of the given dictionary = {1: ['monday'], 2: ['tuesday'], 3: ['wednesday']}<\/pre>\n

Program to invert a Dictionary in Python<\/h2>\n

Below are the ways to invert a given dictionary<\/p>\n