Open In App

Filter List of Python Dictionaries by Key in Python

Last Updated : 27 Dec, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In Python, filtering a list of dictionaries based on a specific key is a common task when working with structured data. In this article, we’ll explore different ways to filter a list of dictionaries by key from the most efficient to the least.

Using List Comprehension

List comprehension is a concise and efficient way to filter dictionaries based on a key.

Python
s = [
    {"name": "Coco", "age": 25},
    {"name": "Cat", "age": 30},
    {"name": "Kay", "age": 35},
    {"name": "Dylan", "age": 40}
]

filtered_people = [p for p in s if p["age"] > 30]

print(filtered_people)

Output
[{'name': 'Kay', 'age': 35}, {'name': 'Dylan', 'age': 40}]
  • We define a list of dictionaries, where each dictionary represents a person with a name and an age.
  • We use list comprehension to filter out the people whose age is greater than 30.

Let's explore some more methods and see how we can filter list of Python dictionaries by key in Python.

Using filter()

filter() function can also be used to filter dictionaries based on a key. This method requires converting the result to a list.

Python
people = [
    {"name": "Coco", "age": 25},
    {"name": "Kate", "age": 30},
    {"name": "Charlie", "age": 35},
    {"name": "David", "age": 40}
]

filtered_people = list(filter(lambda p: p["age"] > 30, people))

print(filtered_people)

Output
[{'name': 'Charlie', 'age': 35}, {'name': 'David', 'age': 40}]

Explanation:

  • The filter() function applies a lambda function that checks if the "age" key in each dictionary is greater than 30. The result is then converted to a list.

Using map()

map() function can be used in combination with a lambda to filter the dictionaries. It’s an alternative functional approach to filter().

Python
a = [
    {"name": "Kay", "age": 25},
    {"name": "Taylor", "age": 30},
    {"name": "Charlie", "age": 35},
    {"name": "David", "age": 40}
]

b = list(map(lambda p: p if p["age"] > 30 else None, a))
b= [p for p in b if p is not None]

print(b)

Output
[{'name': 'Charlie', 'age': 35}, {'name': 'David', 'age': 40}]

Explanation:

  • The map() function applies the condition and returns None for values that don’t meet the condition.
  • After applying map(), we filter out None values with a list comprehension.

Using for Loop

for loop in Python is a more traditional approach to filter dictionaries by key.

Python
a = [
    {"name": "Kate", "age": 25},
    {"name": "Taylor", "age": 30},
    {"name": "Charlie", "age": 35},
    {"name": "David", "age": 40}
]

b = []
for p in a:
    if p["age"] > 30:
        b.append(p)

print(b)

Output
[{'name': 'Charlie', 'age': 35}, {'name': 'David', 'age': 40}]

Explanation:

  • We manually loop through the list and append matching dictionaries.

Next Article

Similar Reads