Lists and Dictionaries are two data structure which is used to store the Data. List stores the heterogeneous data type and Dictionary stores data in key-value pair. Here, we are converting the Python list into dictionary. Since list is ordered and dictionary is unordered so output can differ in order. Python list stores the element in the following way.
student_marks = [56, 78, 96, 37, 85]
On the other hand, Dictionary is unordered, and stores the unique data. It stores the data in key value pair where each key is associated with it value. Python Dictionary stores the data in following way.
student_dict = {'Abhinay': 56, 'Sharma': 78, 'Himanshu': 96, 'Peter': 37}
In this tutorial, we will learn the conversion Python list to dictionary.
Sample Input:
Input : ['Name', 'Abhinay', 'age', 25, 'Marks', 90]
Output : {'Name', 'Abhinay', 'age', 25, 'Marks', 90}
Input : ['a', 10, 'b', 42, 'c', 86]
Output : {'a', 10, 'b', 42, 'c', 86}
Method - 1 Using Dictionary Comprehension
We can convert the list into dictionary using the dictionary comprehension.
Example -
Output:
Explanation -
In the above code, we have created a student list to be converted into the dictionary. Using the dictionary compression, we converted the list in dictionary in a single line. The list elements tuned into key and passed as a value.
Example - 2
Output:
Explanation:
In the above code, we have created square_dict with number-square key/value pair.
Method - 2 Using zip() function
The zip() function is used to zip the two values together. First, we need to create an iterator and initialize to any variable and then typecast to the dict() function.
Example -
Output: