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
Output:
need an explanation for this answer? contact us directly to get an explanation for this answer