
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Convert key-values list to flat dictionary in Python
When it is required to convert a dictionary, that contains pairs of key values into a flat list, dictionary comprehension can be used.
It iterates through the dictionary and zips them using the ‘zip’ method.
The zip method takes iterables, aggregates them into a tuple, and returns it as the result.
Below is a demonstration of the same −
Example
from itertools import product my_dict = {'month_num' : [1, 2, 3, 4, 5, 6], 'name_of_month' : ['Jan', 'Feb', 'March', 'Apr', 'May', 'June']} print("The dictionary is : ") print(my_dict) my_result = dict(zip(my_dict['month_num'], my_dict['name_of_month'])) print("The flattened dictionary is: ") print(my_result)
Output
The dictionary is : {'month_num': [1, 2, 3, 4, 5, 6], 'name_of_month': ['Jan', 'Feb', 'March', 'Apr', 'May', 'June']} The flattened dictionary is: {1: 'Jan', 2: 'Feb', 3: 'March', 4: 'Apr', 5: 'May', 6: 'June'}
Explanation
The required packages are imported into the environment.
A dictionary is defined, and is displayed on the console.
The ‘zip’ method is used to bind the key and value of a dictionary, and it is again converted to a dictionary.
This is assigned to a variable.
It is displayed as output on the console.
- Related Articles
- Sort Dictionary key and values List in Python
- Python - Filter dictionary key based on the values in selective list
- Convert Nested Tuple to Custom Key Dictionary in Python
- Convert a nested list into a flat list in Python
- How to convert list to dictionary in Python?
- Convert dictionary to list of tuples in Python
- Python – Inverse Dictionary Values List
- How to convert Python Dictionary to a list?
- Python – Convert List to Index and Value dictionary
- Python program to get maximum of each key Dictionary List
- How to convert Python dictionary keys/values to lowercase?
- Python program to Convert Matrix to Dictionary Value List
- Combining values from dictionary of list in Python
- Python – Limit the values to keys in a Dictionary List
- Convert string dictionary to dictionary in Python

Advertisements