Python – Filtering a dictionary against a list of values

This short Python snippet shows you how to filter a dictionary against a list of values via the use of a list comprehension.

>>> d = {"apples":1,"bananas":2,"pears":3}
>>> {x:y for x,y in d.iteritems() if x in ["apples","pears"]}
{'apples': 1, 'pears': 3}
Rick Donato

Want to become a programming expert?

Here is our hand-picked selection of the best courses you can find online:
Python Zero to Hero course
Python Pro Bootcamp
Bash Scripting and Shell Programming course
Automate with Shell Scripting course
The Complete Web Development Bootcamp course
and our recommended certification practice exams:
AlphaPrep Practice Tests - Free Trial