How to filter a List of Dictionaries in Python

avatar
Borislav Hadzhiev

Last updated: Apr 10, 2024
4 min

banner

# Table of Contents

  1. How to filter a List of Dictionaries in Python
  2. Filter a List of Dictionaries by unique values
  3. Filter a List of Dictionaries based on a key

# How to filter a List of Dictionaries in Python

To filter a list of dictionaries based on one or multiple values:

  1. Store the acceptable values in a list.
  2. Use a list comprehension to iterate over the list of dictionaries.
  3. Check if the specific key in each dictionary is equal to one of the acceptable values.
main.py
list_of_dictionaries = [ {'id': 1, 'name': 'alice'}, {'id': 2, 'name': 'bobby'}, {'id': 3, 'name': 'carl'}, ] list_of_values = [1, 3] filtered_list_of_dicts = [ dictionary for dictionary in list_of_dictionaries if dictionary['id'] in list_of_values ] # ๐Ÿ‘‡๏ธ [{'id': 1, 'name': 'alice'}, {'id': 3, 'name': 'carl'}] print(filtered_list_of_dicts)

filter list of dictionaries in python

The code for this article is available on GitHub

We stored the acceptable values in a list and used a list comprehension to iterate over the list of dictionaries.

List comprehensions are used to perform some operation for every element or select a subset of elements that meet a condition.

On each iteration, we check if the current dictionary has an id key with one of the values in the list.

The in operator tests for membership. For example, x in l evaluates to True if x is a member of l, otherwise, it evaluates to False.

# Checking for a single value

If you only want to check for a single value, use the equality operator.

main.py
list_of_dictionaries = [ {'id': 1, 'name': 'alice'}, {'id': 2, 'name': 'bobby'}, {'id': 3, 'name': 'carl'}, {'id': 4, 'name': 'bobby'}, ] filtered_list_of_dicts = [ dictionary for dictionary in list_of_dictionaries if dictionary['name'] == 'bobby' ] # ๐Ÿ‘‡๏ธ [{'id': 2, 'name': 'bobby'}, {'id': 4, 'name': 'bobby'}] print(filtered_list_of_dicts)

checking for single value

The code for this article is available on GitHub

The example checks if each dictionary has a name key with a value equal to bobby and returns the result.

The new list only contains the matching dictionaries.

# Filter a list of dictionaries using a for loop

You could also use a for loop to filter a list of dictionaries.

main.py
list_of_dictionaries = [ {'id': 1, 'name': 'alice'}, {'id': 2, 'name': 'bobby'}, {'id': 3, 'name': 'carl'}, ] list_of_values = [1, 3] filtered_list_of_dicts = [] for dictionary in list_of_dictionaries: if dictionary['id'] in list_of_values: filtered_list_of_dicts.append(dictionary) # ๐Ÿ‘‡๏ธ [{'id': 1, 'name': 'alice'}, {'id': 3, 'name': 'carl'}] print(filtered_list_of_dicts)

filter list of dictionaries using for loop

The code for this article is available on GitHub

We used a for loop to iterate over the list of dictionaries.

On each iteration, we check if a certain condition is met.

If the condition is met, we append the current dictionary to a new list.

# Filter a List of Dictionaries by unique values

To filter a list of dictionaries by unique values:

  1. Use a dict comprehension to iterate over the list.
  2. Use the value of each id property as a key and the dictionary as a value.
  3. Use the dict.values() method to only get the unique dictionaries.
  4. Use the list() class to convert the result to a list.
main.py
list_of_dictionaries = [ {'id': 1, 'name': 'alice'}, {'id': 2, 'name': 'bobby'}, {'id': 1, 'name': 'carl'}, ] list_of_unique_dictionaries = list( { dictionary['id']: dictionary for dictionary in list_of_dictionaries }.values() ) # ๐Ÿ‘‡๏ธ [{'id': 1, 'name': 'carl'}, {'id': 2, 'name': 'bobby'}] print(list_of_unique_dictionaries)

filter list of dictionaries by unique values

The code for this article is available on GitHub

We used a dict comprehension to iterate over the list of dictionaries.

Dict comprehensions are very similar to list comprehensions.

They perform some operation for every key-value pair in the dictionary or select a subset of key-value pairs that meet a condition.

On each iteration, we set the value of the current id as the key and the actual dictionary as the value.

The keys in a dictionary are unique, so any duplicate values get filtered out.

We then use the dict.values() method to only return the unique dictionaries.

The dict.values() method returns a new view of the dictionary's values.

main.py
my_dict = {'id': 1, 'name': 'bobbyhadz'} print(my_dict.values()) # ๐Ÿ‘‰๏ธ dict_values([1, 'bobbyhadz'])

The last step is to use the list() class to convert the view object to a list containing unique dictionaries.

# Filter a list of dictionaries based on a key

To filter a list of dictionaries based on a key:

  1. Use a list comprehension to iterate over the list of dictionaries.
  2. Use the dict.get() method to check if each dictionary contains the given key.
  3. The new list will only contain the dictionaries that contain the key.
main.py
list_of_dictionaries = [ {'id': 1, 'name': 'alice'}, {'id': 2, 'name': 'bobby'}, {'id': 3, 'salary': 100}, ] filtered_list = [ dictionary for dictionary in list_of_dictionaries if dictionary.get('name') is not None ] # ๐Ÿ‘‡๏ธ [{'id': 1, 'name': 'alice'}, {'id': 2, 'name': 'bobby'}] print(filtered_list)
The code for this article is available on GitHub

We used a list comprehension to iterate over the list of dictionaries.

On each iteration, we use the dict.get() method to check if the current dictionary contains the name key.

The dict.get() method returns the value for the given key if the key is in the dictionary, otherwise a default value is returned.

The method takes the following 2 parameters:

NameDescription
keyThe key for which to return the value
defaultThe default value to be returned if the provided key is not present in the dictionary (optional)

If a value for the default parameter is not provided, it defaults to None, so the get() method never raises a KeyError.

The new list only contains the dictionaries that contain the given key.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.

Copyright ยฉ 2024 Borislav Hadzhiev