Convert key-values list to flat dictionary in Python

PythonServer Side ProgrammingProgramming

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

 Live Demo

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.

raja
Published on 14-Apr-2021 12:38:23
Advertisements