Python program to Convert key-values list to flat dictionary
In this tutorial, we will learn how to write a program that will convert a key-value list to a flat dictionary using the Python programing language. For a given dictionary with pairs of key-value as a list, we have to convert this list to a flat dictionary. A dictionary can be flattened by pairing the same index elements together.
Let us look at the sample input-output of the program.
Input: { "num": [1, 2, 3], "name": ['Monica', 'Joey', 'Jane' ] }
Output: {1: 'Monica', 2: 'Joey', 3: 'Jane'}
To solve this problem in Python, we can use a combination of methods of the dictionary class- zip()
and dict()
. If you want to know more about dictionary functions in Python.
The zip()
method is a built-in function that accepts iterables as parameters and returns a tuple of the elements from each iterable
The dict()
method is a built-in function used to create a dictionary in Python.
Algorithm
Follow the algorithm to understand the approach better.
Step 1- Initialise dictionary with key and list values
Step 2- Print original dictionary
Step 3- Declare another dictionary that will store the elements grouped together
Step 4- Use zip() to get the elements in the dictionary in the form of a tuple
Step 5- Use dict() to convert the tuple to a dictionary
Step 6- Print the new dictionary as the result
Python Program
Look at the program to understand the implementation of the above-mentioned approach. We have declared a new dictionary that will be the flattened dictionary and will have the same index elements grouped together.
dic= { "day": [1, 2, 3], "name": ['Mon', 'Tues', 'Wed' ] }
print("Original dictionary: ",dic)
# convert to flat dictionary
f_dic= dict(zip(dic["day"], dic["name"]))
print("FLATTENED DICTIONARY: ", f_dic)
Original dictionary: {'day': [1, 2, 3], 'name': ['Mon', 'Tues', 'Wed']}
FLATTENED DICTIONARY: {1: 'Mon', 2: 'Tues', 3: 'Wed'}
Conclusion
In this tutorial, we have learned what is a flat dictionary and how to convert a pair of key-value where value is a list into a flat dictionary. We have used the zip()
method and the dict()
method to execute this task.