Q:

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

belongs to collection: Python Dictionary Programs

0

Python programming language is a high-level and object-oriented programming languagePython 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.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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}

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Python Dictionary Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Python program to insert an element at the beginni... >>
<< How to remove a key from dictionary in Python?...