Last Updated on May 6, 2024 by Roshan Parihar
To convert two Lists into a Dictionary in Python, use the dict()
function inside which you have to use the zip()
function.
You can also use the for loop to create a Dictionary from two Lists using Python. Let’s find out the different useful examples given below here.
How to Convert Two Lists Into Dictionary Using dict() with zip() in Python?
If you want to convert the two Lists into a Dictionary, you have to use the dict()
function of Python. Inside this function, you have to use the zip()
function and pass the comma-separated two Lists variables as its arguments. The result gives the converted two Lists into a Dictionary.
1 2 3 4 5 6 7 8 9 |
#Declare two List variables in Python ListKeys = ["Billy", "John", "Rock"]; ListValues = [11, 23.9, 19]; #Convert two Lists into a Dictionary using zip() mergeLists = dict(zip(ListKeys, ListValues)) #Print new Dictionary print("Dictionary after conversion is: "+str(mergeLists)) |
Output
The above example shows the output in which the first List becomes keys and the second List becomes values.
Using For Loop to Change Two Lists into a Dictionary in Python
You can change the two Lists into Dictionary using the for loop of Python. Firstly, you have to define a blank Dictionary variable in Python. After that, use the for loop and store the keys and values to Dictionary in each iteration.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
#Declare two List variables in Python ListKeys = ["Billy", "John", "Rock"]; ListValues = [11, 23.9, 19]; #Convert two Lists into a Dictionary using for loop myDict = {} d = 0 for i in ListKeys: myDict[i] = ListValues[d] d += 1 #Print new Dictionary print("Dictionary after conversion is: "+str(myDict)) |
Output
The output contains the same Dictionary variable and its elements that you get in the first example above. It takes some time to run the loop and add the items to the Dictionary in each iteration.
Using Dictionary Comprehension in Python
In addition to the above methods, you can also use Dictionary comprehension to create a Dictionary from two list variables. See the example given below to learn the method of using the Dictionary comprehension using Python.
1 2 3 4 5 6 7 8 9 |
#Declare two List variables in Python ListKeys = ["Billy", "John", "Rock"]; ListValues = [11, 23.9, 19]; #Convert two Lists into a Dictionary using zip() mergeLists = {ListKeys[i]: ListValues[i] for i in range(len(ListKeys))} #Print new Dictionary print("Dictionary after conversion is: "+str(mergeLists)) |
Output
When you execute the above code, you will also get the same result as the first and second examples above.
You May Also Like to Read