Python | Convert two lists to a dictionary

Method # 1: The Naive Method
The main method that can be used to accomplish this task is the brute force method to achieve this goal. To do this, simply declare a dictionary and then run a nested loop on both lists and assign key and value pairs from the list values ​​to the dictionary.

# Python3 demo code
# converting lists to a dictionary
# using a naive method

 
# initializing lists

test_keys = [ "Rash" , " Kil " , " Varsha " ]

test_values ​​ = [ 1 , 4 , 5 ]

 
# Prints original key value lists

print ( "Original key list is: " + str (test_keys))

print ( "Original value list is:" + str (test_values))

 
# using the naive method
# convert lists to a dictionary

res = {} < / p>

for key in test_keys:

  for value in test_values:

res [key] = value

test_values.remove (value)

break  

 
# Print the resulting dictionary

print ( "Resultant dictionary is : " +   str (res))

Exit:

 Original key list is: ['Rash',' Kil' , 'Varsha'] Original value list is: [1, 4, 5] Resultant dictionary is: {' Varsha': 5, 'Rash': 1,' Kil': 4} 

Method # 2: Using vocabulary comprehension
A shorter way to implement the above method — is a dictionary comprehension technique that offers a faster and more time-saving approach by reducing the number of lines to type.

# Python3 demo code
# converting lists to a dictionary
# using dictionary comprehension

  
# initializing lists

test_keys = [ "Rash" , "Kil" , "Varsha" ]

test_values ​​ = [ 1 , < / code> 4 , 5 ]

 
# Print original key value lists

print ( "Original key list is:" + str (test_keys))

print ( "Original value list is:" + str (test_values))

  
# using dictionary comprehension
# convert lists to dictionary

res = {test_keys [i]: test_values ​​[i] for i in range ( len (test_keys ))}

 
# Print the resulting dictionary

print ( "Resultant dictionary is:" +   str (res))

Exit:

 Original key list is: ['Rash',' Kil', 'Varsha' ] Original value list is: [1, 4, 5] Resultant dictionary is: {'Varsha': 5,' Kil': 4, 'Rash': 1} 

Method # 3: Using zip()
The most pythonic and versatile method to accomplish this very task is to use zip ( ) . This function associates a list item with another list item at the corresponding index as key-value pairs.

# Python3 demo code
# converting lists to a dictionary
# using zip ()

  
# initializing lists

test_keys = [ "Rash" , "Kil" , "Varsha" ]

test_values ​​ = [ 1 , 4 , 5 ]

 
# Print original key value lists

print ( "Original key list is:" + str (test_keys))

print ( "Original value list is:" + str (test_values))

 
# using zip ()
# convert lists to dictionary

res = dict ( zip (test_keys, test_values))

  
# Print the resulting dictionary

print ( "Resultant dictionary is:" +   str (res))

Exit:

 Original key list is: ['Rash',' Kil', 'Varsha'] Original value list is: [1, 4, 5] Resultant dictionary is: {' Kil': 4, 'Rash': 1,' Varsha': 5} 




Get Solution for free from DataCamp guru