Convert two lists into a dictionary in Python

PythonServer Side ProgrammingProgramming

While a Python list contains a series of values a dictionary on the other hand contains a pair of values which are called key-value pairs. In this article we will take two lists and mark them together to create a Python dictionary.

With for and remove

We create two nested for loops. In the inner loop will assign one of the list as key for the dictionary while keep removing the values from the list which is outer for loop.

Example

 Live Demo

listK = ["Mon", "Tue", "Wed"]
listV = [3, 6, 5]
# Given lists
print("List of K : ", listK)
print("list of V : ", listV)
# Empty dictionary
res = {}
# COnvert to dictionary
for key in listK:
   for value in listV:
      res[key] = value
      listV.remove(value)
      break
print("Dictionary from lists :\n ",res)

Output

Running the above code gives us the following result −

('List of K : ', ['Mon', 'Tue', 'Wed'])
('list of V : ', [3, 6, 5])
('Dictionary from lists :\n ', {'Wed': 5, 'Mon': 3, 'Tue': 6})

With for and range

The two lists are combined to create a pair of values by putting them into a for loop. The range and len functions are used to keep track of the number of elements till all the key value pairs are created.

Example

 Live Demo

listK = ["Mon", "Tue", "Wed"]
listV = [3, 6, 5]
# Given lists
print("List of K : ", listK)
print("list of V : ", listV)
# COnvert to dictionary
res = {listK[i]: listV[i] for i in range(len(listK))}
print("Dictionary from lists :\n ",res)

Output

Running the above code gives us the following result −

('List of K : ', ['Mon', 'Tue', 'Wed'])
('list of V : ', [3, 6, 5])
('Dictionary from lists :\n ', {'Wed': 5, 'Mon': 3, 'Tue': 6})

With zip

The zip function does something similar to above approach. It also combines the elements from the two lists, creating key and value pairs.

Example

 Live Demo

listK = ["Mon", "Tue", "Wed"]
listV = [3, 6, 5]
# Given lists
print("List of K : ", listK)
print("list of V : ", listV)
# COnvert to dictionary
res = dict(zip(listK, listV))
print("Dictionary from lists :\n ",res)

Output

Running the above code gives us the following result −

('List of K : ', ['Mon', 'Tue', 'Wed'])
('list of V : ', [3, 6, 5])
('Dictionary from lists :\n ', {'Wed': 5, 'Mon': 3, 'Tue': 6})
raja
Published on 04-Jun-2020 14:44:48
Advertisements