How to Filter a List of Dictionaries in Python?

In this article, you’ll learn how to filter a list of dictionaries. So let’s get started!

Short answer: The list comprehension statement [x for x in lst if condition(x)] creates a new list of dictionaries that meet the condition. All dictionaries in lst that don’t meet the condition are filtered out. You can define your own condition on list element x.

Here’s a quick and minimal example:

l = [{‘key’:10}, {‘key’:4}, {‘key’:8}]

def condition(dic):
”’ Define your own condition here”’
return dic[‘key’] > 7

filtered = [d for d in l if condition(d)]

# [{‘key’: 10}, {‘key’: 8}]

Try it yourself in the interactive Python shell (in

Continue reading the original article