Create a Dictionary from two lists using dictionary comprehension in Python

In this tutorial, we will create a Dictionary from two lists using dictionary comprehension in Python

Before we begin, let's define two lists students and marks such that the appear as follows.

students = [ 'Bob', 'Alice', 'Ram', 'Geeta', 'Shreyan', 'Raj']
marks = [ 60, 43, 80, 49, 95, 68]
Defining two lists students and marks in Python

The aforementioned lists students and marks are of same length with six elements in each. The elements in both the lists represent students and their respective marks. For example, a student named Shreyan has scored 95 marks in a given exam.

We will create a dictionary where the keys will be student names and values will be the marks. We will now create dictionary of students with respective marks using list comprehension applied on a dictionary often referred to as dictionary comprehension given that we have two lists.

students = [ 'Bob', 'Alice', 'Ram', 'Geeta', 'Shreyan', 'Raj']
marks = [ 60, 43, 80, 49, 95, 68]

d1 = { s:m for s,m in zip(students, marks)}
    
print(d1)
Create a Dictionary using two lists of same length using dictionary comprehension in Python

In the preceding code, we have used zip to iterate through both the lists at the same time with the respective index in each iteration being the same.

We have followed the approach of adding key value pair to the dictionary in Python using dictionary comprehension.

When building a dictionary using dictionary comprehension, we can observe two things as follows.

  • The colon operator :.When adding key value pair to the dictionary, we have followed the syntax of : to separate key and value which is identified by s:m. The s being the representation of key, which is student name for each iteration. And m being the representation of value, which is the mark obtained by student in the same iteration performed by for key word.
  • The opening { and closing } squiggly braces holding the whole dictionary comprehension style of building a dictionary.

The output will appear as follows.

{'Bob': 60, 'Alice': 43, 'Ram': 80, 'Geeta': 49, 'Shreyan': 95, 'Raj': 68}
Output: Create a Dictionary using two lists of same length using dictionary comprehension in Python

From the preceding output, we notice that we resultant dictionary is built using the dictionary comprehension by combining two lists. The result is the key value representation after zipping the two lists students and marks respectively.