Editor

Python Program to Create a Dictionary from Two Lists

Beginner · Dictionaries

Two lists often belong together, like a list of names and a list of their marks. This program pairs the first item of one list with the first item of the other, and so on, and stores the pairs in a dictionary with the first list as the keys.

Program

dictionary_from_two_lists.py
names = ["Riya", "Arjun", "Meera", "Kabir"]
marks = [88, 72, 95, 64]
result = {}
for i in range(len(names)):
result[names[i]] = marks[i] # the name is the key, the mark is the value
print("Keys: ", names)
print("Values:", marks)
print("Dictionary:", result)
print("Meera scored", result["Meera"])
Output
Keys:   ['Riya', 'Arjun', 'Meera', 'Kabir']
Values: [88, 72, 95, 64]
Dictionary: {'Riya': 88, 'Arjun': 72, 'Meera': 95, 'Kabir': 64}
Meera scored 95

How it works

  1. The loop runs once for each position i in the list of names.
  2. result[names[i]] = marks[i] adds an entry whose key is the name at that position and whose value is the mark at the same position.
  3. Once the dictionary is built, a mark can be looked up by name, like result["Meera"], instead of by position.
  4. Keys are unique, so if a name appeared twice in names, the later mark would replace the earlier one.
  5. The loop expects the lists to be the same length; if marks were shorter, marks[i] would raise an IndexError.

Other ways to write it

Using zip()

Using zip()
names = ["Riya", "Arjun", "Meera", "Kabir"]
marks = [88, 72, 95, 64]
result = dict(zip(names, marks))
print("Dictionary:", result)
Output
Dictionary: {'Riya': 88, 'Arjun': 72, 'Meera': 95, 'Kabir': 64}

zip() pairs the lists item by item, and dict() turns the pairs into a dictionary. This is the standard one-line way.

When the lists have different lengths

When the lists have different lengths
from itertools import zip_longest
names = ["Riya", "Arjun", "Meera"]
marks = [88, 72]
print("zip(): ", dict(zip(names, marks)))
print("zip_longest():", dict(zip_longest(names, marks, fillvalue="absent")))
Output
zip():         {'Riya': 88, 'Arjun': 72}
zip_longest(): {'Riya': 88, 'Arjun': 72, 'Meera': 'absent'}

zip() stops at the end of the shorter list, so Meera is silently dropped, while zip_longest() keeps going and fills the gap with fillvalue.

Try it yourself

Make a dictionary from ["a", "b", "c"] and [1, 2, 3], then swap the lists so the numbers become the keys.

Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.

All Python programs · CBSE class 12 practical file · Python exercises