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
Keys: ['Riya', 'Arjun', 'Meera', 'Kabir']
Values: [88, 72, 95, 64]
Dictionary: {'Riya': 88, 'Arjun': 72, 'Meera': 95, 'Kabir': 64}
Meera scored 95How it works
- The loop runs once for each position
iin the list of names. 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.- Once the dictionary is built, a mark can be looked up by name, like
result["Meera"], instead of by position. - Keys are unique, so if a name appeared twice in
names, the later mark would replace the earlier one. - The loop expects the lists to be the same length; if
markswere shorter,marks[i]would raise an IndexError.
Other ways to write it
Using zip()
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
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.
Related programs
All Python programs · CBSE class 12 practical file · Python exercises