Create a Dictionary using dictionary comprehension along with if condition in Python
In this tutorial, we will create a Dictionary using dictionary comprehension along with if condition in Python
Before we begin, let's define two lists students and marks such that the appear as follows.
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 and whose marks are greater than 70. We will now create dictionary of student with respective marks using dictionary comprehension given that we have two lists along with conditional adding of items to the dictionary.
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.
This time, in addition to adding items to a dictionary using dictionary comprehension, the if condition is added to filter students whose marks are > 70 using the if condition added at the end of the dictionary comprehension. The output in this case will be as follows.
From the preceding output, we notice that the resultant dictionary based on the if condition applied in our dictionary comprehension, printed the students whose marks are greater than 70.