
- Python 3 Basic Tutorial
- Python 3 - Home
- What is New in Python 3
- Python 3 - Overview
- Python 3 - Environment Setup
- Python 3 - Basic Syntax
- Python 3 - Variable Types
- Python 3 - Basic Operators
- Python 3 - Decision Making
- Python 3 - Loops
- Python 3 - Numbers
- Python 3 - Strings
- Python 3 - Lists
- Python 3 - Tuples
- Python 3 - Dictionary
- Python 3 - Date & Time
- Python 3 - Functions
- Python 3 - Modules
- Python 3 - Files I/O
- Python 3 - Exceptions
Python – Inverse Dictionary Values List
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.
- Related Articles
- Combining values from dictionary of list in Python
- Sort Dictionary key and values List in Python
- Python - Create a dictionary using list with none values
- Convert key-values list to flat dictionary in Python
- Python – Limit the values to keys in a Dictionary List
- How to create Python dictionary from list of keys and values?
- Python - Filter dictionary key based on the values in selective list
- How to get a list of all the values from a Python dictionary?
- Accessing Values of Dictionary in Python
- Python - Clearing list as dictionary value
- Python – Create dictionary from the list
- Append Dictionary Keys and Values (In order ) in dictionary using Python
- How to update a Python dictionary values?
- Extract Unique dictionary values in Python Program
- How do I sort a list of dictionaries by values of the dictionary in Python?

Advertisements