How to Filter a Dictionary in Python

Spread the love

Problem –

You have a dictionary and you want to filter it based on key or value of the dictionary.

Solution –

The easiest way to accomplish this is using a dictionary comprehension.

Let’s say we have some students scores in a dictionary.

In [1]: scores = {'Amit': 30,
   ...:         'subodh':60,
   ...:         'Mark':40,
   ...:         'Nathan':70,
   ...:         'Rakesh':80}

And we want to filter all the students who scored more than 50.

In [2]: high_marks = {key: value for key, value in scores.items() if value > 50}

In [3]: high_marks
Out[3]: {'subodh': 60, 'Nathan': 70, 'Rakesh': 80}

we can also filter the keys like this.

In [4]: # dictionary of indian students

In [5]: indian_students = {'Amit','subodh','Rakesh'}

In [6]: indians = {key: value for key, value in scores.items() if key in indian_students}

In [7]: indians
Out[7]: {'Amit': 30, 'subodh': 60, 'Rakesh': 80}

Rating: 1 out of 5.

Leave a Reply