Learn Python – How to convert list to dictionary in Python- Basic and advance

Lists and Dictionaries are two facts structure which is used to shop the Data. List stores the heterogeneous statistics kind and Dictionary shops records in key-value pair. Here, we are changing the Python listing into dictionary. Since listing is ordered and dictionary is unordered so output can fluctuate in order. Python list stores the issue in the following way.

student_marks = [56, 78, 96, 37, 85]  

On the other hand, Dictionary is unordered, and shops the unique data. It shops the statistics in key cost pair the place each key is associated with it value. Python Dictionary shops the statistics in following way.

student_dict = {'Abhinay': 56, 'Sharma': 78, 'Himanshu': 96, 'Peter': 37}  

In this tutorial, we will research the conversion Python listing 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}  

Let’s understand the following methods.

Method – 1 Using Dictionary Comprehension

We can convert the listing into dictionary the usage of the dictionary comprehension. Let’s understand the following code.

Example –

student = ["James", "Abhinay", "Peter", "Bicky"]  
  
student_dictionary = { stu : "Passed" for stu in student }  
  
print(student_dictionary)  

Output:

{'James': 'Passed', 'Abhinay': 'Passed', 'Peter': 'Passed', 'Bicky': 'Passed'}

Explanation –

In the above code, we have created a student listing to be transformed into the dictionary. Using the dictionary compression, we transformed the listing in dictionary in a single line. The listing factors tuned into key and handed as a value.

Let’s understand another example.

Example – 2

list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]  
square_dict = {n: n*n for n in list1}  
print(square_dict)  

Output:

{1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81, 10: 100}

Explanation:

In the above code, we have created square_dict with number-square key/value pair.

Method – 2 Using zip() function

The zip() characteristic 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.

Let’s understand the following example.

Example –

def Convert_dict(a):  
    init = iter(list1)  
    res_dct = dict(zip(init, init))  
    return res_dct  
  
  
# Driver code  
list1 = ['x', 1, 'y', 2, 'z', 3]  
print(Convert_dict(list1))  

Output:

{'x': 1, 'y': 2, 'z': 3}