Python program to convert key-value list to flat dictionary – Dictionary Flattening

Here, we will see a Python program to convert a dictionary with key-value list to a flat dictionary.
Submitted by Shivang Yadav, on May 22, 2021

Python programming language is a high-level and object-oriented programming language. Python is an easy to learn, powerful high-level programming language. It has a simple but effective approach to object-oriented programming.

Dictionary is a collection in python which is used to store data as Key:value pair.

Example:

dict = { "python" : 1, "C++" : 3, "javaScript" : 2 } 

Convert key-value list to flat dictionary in python

We are given a dictionary with key-value as a list and convert this into a flat dictionary using Python's built-in function.

There are dictionaries in Python which need to be flattened for processing and pairing the elements which have the same index value for processing the data stored in it.

Input:
dict = 
    {
    'language' : ['python', 'java', 'c/c++', 'javascript'], 
    'year' : [1991, 1995, 1980, 1995]
    }

Output:
flatDict : {'python' : 1991 , 'java' : 1995, 'c/c++' : 1980, 'javascript' : 1995}

In Python programming, it is possible to flatten a dictionary, we need to extract the value list from this dictionary and then use the value as key-value pairs to form a dictionary.

This process requires two functions that are present in python.

  • zip() method to convert list into tuple list.
  • dict() method to return a dictionary from the input values.

Program to convert key-value list to flat dictionary

# Python program to convert key-value list to flat dictionary

# Printing original dictionary 
languages = {'language' : ['python', 'java', 'c/c++', 'javascript'], 'year' : [1991, 1995, 1980, 1995]}

print("dictionary languages : " + str(languages))

# Flattening dictionary 
lang_year = dict(zip(languages['language'], languages['year']))

# Printing Flattened dictionary 
print("Flattened dictionary  language : " + str(lang_year))

Output:

dictionary languages : {'year': [1991, 1995, 1980, 1995], 'language': ['python', 'java', 'c/c++', 'javascript']}
Flattened dictionary  language : {'java': 1995, 'javascript': 1995, 'c/c++': 1980, 'python': 1991}

Python Dictionary Programs »



Related Programs



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.