How to Make a Dictionary from Two Lists in Python

Creating a dictionary from two lists is a simple task, but it often gets overlooked. Here’s how you can do it.

Updated November 6, 2023

Creating a dictionary from two lists is a simple task, but it often gets overlooked. Here’s how you can do it.

Sometimes, we have two lists and need them combined into one dictionary where each element of the first list corresponds to an element in the second list. This can be useful when you want to combine related data from different sources or when you are working with a database.

To make a dictionary from two lists, we use Python’s built-in function called zip(). This function combines elements of each iterable and returns a zip object, which is an iterator of tuples where the first item in each passed iterator is paired together, and then the second item in each passed iterator are paired together.

Here’s how you can do it:

list1 = [1,2,3,4,5] # The first list.
list2 = ['a','b','c','d','e'] # The second list.

dictionary = dict(zip(list1, list2)) 
# The `zip()` function makes a zip object, which is an iterator of tuples where the first item in each passed iterator are paired together and so on. The `dict()` function then converts this into a dictionary.

In this case, the resulting dictionary would be: {1: 'a', 2: 'b', 3: 'c', 4: 'd', 5: 'e'}.

This is often useful when you have two lists that logically correspond to each other. For example, if your list1 contains student IDs and list2 contains their respective names, then this method can be very convenient for quickly creating a dictionary where the keys are the student IDs and the values are the student names.

Stay up to date on the latest in Coding Python with AI and Data Science

Intuit Mailchimp