
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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.
Advertisements