Filter Dictionary Python [3 Methods+ Examples]

In this Python tutorial, I will explain how to filter dictionary Python using different methods in Python, with some illustrative examples. In the process, we will also see different ways to filter dict Python.

Before diving into the Python filter dictionary techniques, let’s briefly revisit the basics of dictionaries. A Python dictionary consists of keys and values. Each key maps to a unique value, which means that keys must be unique.

For example, Imagine we are tasked with creating a program to store details about US states. For each state, we want to store its capital city. This is a great use case for a Python dictionary.

states_and_capitals = {
    "California": "Sacramento",
    "Texas": "Austin",
    "New York": "Albany",
    "Florida": "Tallahassee",
    "Illinois": "Springfield"
}
print('The name of the data-type we created:', type(states_and_capitals))

Output: In this Python dictionary:

  • The states’ names (e.g., “California”, “Texas”, “New York”) are the keys.
  • The capitals (e.g., “Sacramento”, “Austin”, “Albany”) are the values.
The name of the data-type we created: <class 'dict'>
filter dictionary python

This way we can create a Python dictionary.

Imagine we are working with a vast amount of data stored in a Python dictionary– like information from a national census or sales data from all fifty states. Often, we don’t need all the data but only specific subsets that meet certain criteria. In such cases, filtering that data becomes essential. So, we need to filter Python dictionary.

Methods to Filter Dictionary Python

There are three different methods present in Python to filter a dictionary.

  • Using for loop
  • The dictionary comprehension
  • The filter() function with lambda expression

Let’s see them one by one using different illustrative examples:

Method 1: The Classic For Loop Approach to Filter Dict Python

A straightforward way to Python filter dict entries is by looping through the dictionary using a for loop and storing the required entries in a new Python dictionary.

Example: Suppose we have a Python dictionary of states and their GDP values. We want to filter dictionary python entries to only show states with GDP values greater than 1 trillion.

state_gdp = {
    'California': 3.1,
    'Texas': 1.8,
    'New York': 1.7,
    'Florida': 1.0,
    'Illinois': 0.8
}
high_gdp_states = {}
for state, gdp in state_gdp.items():
    if gdp > 1:
        high_gdp_states[state] = gdp
print(high_gdp_states)

The output is: States with a GDP greater than 1 trillion:

{'California': 3.1, 'Texas': 1.8, 'New York': 1.7}
python filter dictionary

This way we can use a for loop to filter a dictionary Python.

Method 2: The Dictionary Comprehension Method for Python dict Filter

For a more Pythonic solution, dictionary comprehensions come in handy. They offer a concise way to Python dict filter entries.

Scenario: We have a dictionary in Python of states and their populations. We want to Python filter dictionary by value to display states with populations greater than 20 million.

state_population = {
    'California': 39.5,
    'Texas': 28.7,
    'New York': 19.5,
    'Florida': 21.5,
    'Illinois': 12.7
}
high_population_states = {state: population for state, population in state_population.items() if population > 20}
print(high_population_states)

Output:

{'California': 39.5, 'Texas': 28.7, 'Florida': 21.5}
python filter dict by value

This way we can use dict comprehension for Python filter dictionary by value.

Method 3: Using the filter function in Python to filter dict

Lambda expression offers concise ways to define functions on the fly. Coupled with the filter() function, we can achieve powerful Python filter dictionary lambda operations.

Scenario: We have a Python dict of states and their average temperatures. We want to Python filter dictionary by value lambda to include states with average temperatures below 50°F.

state_temperature = {
    'Alaska': 34,
    'Texas': 65,
    'New York': 52,
    'Minnesota': 41,
    'Florida': 70
}
cold_states = dict(filter(lambda item: item[1] < 50, state_temperature.items()))
print(cold_states)

Output:

{'Alaska': 34, 'Minnesota': 41}
python dict filter lambda

This is how to filter dictionary in Python works with the filter function with lambda expression.

Ways for Python dictionary filter

Depending on our requirements, we may want to

  • filter dictionary Python by key.
  • filter dictionary Python by value.
  • Python filter dictionary by key value

Filter dictionary Python by key

We can in Python filter dictionary by key using a dictionary comprehension.

Scenario: From a Python dictionary of state birds, filter states starting with the letter ‘M’.

state_birds = {
    'Maine': 'Chickadee',
    'Texas': 'Mockingbird',
    'Mississippi': 'Mockingbird',
    'Florida': 'Mockingbird',
    'Minnesota': 'Common loon'
}
m_states = {state: bird for state, bird in state_birds.items() if state.startswith('M')}
print(m_states)

The output displays:

{'Maine': 'Chickadee', 'Mississippi': 'Mockingbird', 'Minnesota': 'Common loon'}
python dict filter keys

This way we can Python filter dict by keys.

Python filter dictionary by value lambda

Scenario: From a Python dictionary of state names and their state flowers, filter out states whose names are longer than seven characters using the filter() function.

state_flowers = {
    'California': 'Golden Poppy',
    'Texas': 'Bluebonnet',
    'Mississippi': 'Magnolia',
    'Florida': 'Orange Blossom',
    'Indiana': 'Peony'
}
long_flower_name = dict(filter(lambda item: len(item[1]) >7, state_flowers.items()))
print(long_flower_name)

Output: The lambda function in Python checks the length of the state name and filters accordingly.

{'California': 'Golden Poppy', 'Texas': 'Bluebonnet', 'Mississippi': 'Magnolia', 'Florida': 'Orange Blossom'}
python filter dictionary by key value

This way we can Python filter dictionary lambda with values.

Filtering Python Dictionary By Both Key and Value

To Python filter dictionary by key value, we can combine conditions in dictionary comprehensions:

For instance, Consider a Python dictionary where the keys are the names of some US presidents and the values are the states they were born in. We need to filter for presidents born in states that start with the letter ‘V’ and have names ending with the letter ‘n’.

president_birth_states = {
    'George Washington': 'Virginia',
    'John Adams': 'Massachusetts',
    'Thomas Jefferson': 'Virginia',
    'Barack Obama': 'Hawaii',
    'Donald Trump': 'New York'
}
filtered_presidents = {key: value for key, value in president_birth_states.items() if key.endswith('n') and value.startswith('V')}
print(filtered_presidents)

Output:

{'George Washington': 'Virginia', 'Thomas Jefferson': 'Virginia'}
python filter dictionary by key

This way we can filter dict in Python with key and value.

Note: We can also use Python lambda filter dictionary with filter() function to filter dict with key and value.

filtered_items = filter(lambda item: item[0].endswith('n') and item[1].startswith('V'), president_birth_states.items())
filtered_presidents = dict(filtered_items)
print(filtered_presidents)
python filter dict lambda

Performance Considerations in Filter Dictionary in Python

When working with a significantly large dictionary in Python, efficiency becomes crucial. Here are a few tips:

  • Pre-process Data: Instead of frequently filtering a Python dictionary, pre-process our data. Store subsets of the Python dictionary that we access regularly.
  • Use Built-in Functions: Built-in functions and methods are optimized for performance in Python. For instance, using the items() method to iterate over a Python dictionary is faster than accessing keys and values separately.

Conclusion

This tutorial explains how to filter dictionary Python using three different methods such as for loop, dictionary comprehension, or filter() function with lambda with demonstrative examples, We have also seen different ways to filter Python dict such as with only keys, only values, or both with keys and values.

Filtering dictionaries in Python is a powerful technique, especially when dealing with large datasets. By understanding dictionary comprehensions and employing filter functions, we can efficiently process and extract essential information from our data.

You may also like to read: