Constructing a new dict:

dict_you_want = {key: old_dict[key] for key in your_keys}

Uses dictionary comprehension.

If you use a version which lacks them (ie Python 2.6 and earlier), make it dict((key, old_dict[key]) for ...). It's the same, though uglier.

Note that this, unlike jnnnnn's version, has stable performance (depends only on number of your_keys) for old_dicts of any size. Both in terms of speed and memory. Since this is a generator expression, it processes one item at a time, and it doesn't looks through all items of old_dict.

Removing everything in-place:

unwanted = set(old_dict) - set(your_keys)
for unwanted_key in unwanted: del your_dict[unwanted_key]
Answer from user395760 on Stack Overflow
🌐
GeeksforGeeks
geeksforgeeks.org › python › filter-list-of-dictionaries-based-on-key-values-in-python
Filter List of Dictionaries Based on Key Values in Python - GeeksforGeeks
July 23, 2025 - The filter() function is another way to filter a list. The filter() function applies a condition to each dictionary in people. We use a lambda function to check if the value of the 'role' key is in the f list.
Discussions

python - Filter dict to contain only certain keys? - Stack Overflow
Only works in Python 3. Python ... for -: 'list' and 'set'" 2019-05-27T19:45:56.52Z+00:00 ... Added set(d.keys()) for Python 2. This is working when I run. 2019-05-28T04:29:18.647Z+00:00 ... According to the title of the question, one would expect to filter the dictionary in place - ... More on stackoverflow.com
🌐 stackoverflow.com
python filter list of dictionaries based on key value - Stack Overflow
I have a list of dictionaries and each dictionary has a key of (let's say) 'type' which can have values of 'type1', 'type2', etc. My goal is to filter out these dictionaries into a list of the same More on stackoverflow.com
🌐 stackoverflow.com
python - Filter a dictionary from a list of keys - Stack Overflow
I want to filter a dictionary based on a set/list/(dict) of keys. Currently I'm using a generator like this: def filter_dict(in_dict, in_iterator): for key, value in in_dict.items(): ... More on stackoverflow.com
🌐 stackoverflow.com
Python - Filter list of dictionaries based on multiple keys - Stack Overflow
As seen in the list dictionary in myDict list, the dictionary DOESNT have to have both keys in order to be placed into filteredDict. Is there an easy way to do this with dictionary comprehension in Python? More on stackoverflow.com
🌐 stackoverflow.com
🌐
AskPython
askpython.com › python › dictionary › filter-list-of-dictionaries-based-on-key-values
3 Ways to Filter List of Dictionaries Based on Key Values - AskPython
April 27, 2023 - To filter a list of dictionaries, we need to have a condition that needs to be satisfied by the keys of the dictionary to create a new filtered dictionary. A dictionary is the most popularly used data storage structure of Python.
🌐
TutorialsPoint
tutorialspoint.com › article › python-filter-dictionary-key-based-on-the-values-in-selective-list
Python - Filter dictionary key based on the values in selective list
# Original dictionary dictA = {'Mon': 'Phy', 'Tue': 'chem', 'Wed': 'Math', 'Thu': 'Bio'} key_list = ['Tue', 'Thu', 'Fri'] # Note: 'Fri' doesn't exist in dictA print("Given Dictionary:") print(dictA) print("Keys for filter:") print(key_list) # Find intersection of keys common_keys = list(set(key_list).intersection(dictA.keys())) print("Common keys found:") print(common_keys) # Create filtered dictionary filtered_dict = {key: dictA[key] for key in common_keys} print("Filtered dictionary:") print(filtered_dict)
Top answer
1 of 4
238

You can try a list comp

>>> exampleSet = [{'type':'type1'},{'type':'type2'},{'type':'type2'}, {'type':'type3'}]
>>> keyValList = ['type2','type3']
>>> expectedResult = [d for d in exampleSet if d['type'] in keyValList]
>>> expectedResult
[{'type': 'type2'}, {'type': 'type2'}, {'type': 'type3'}]

Another way is by using filter

>>> list(filter(lambda d: d['type'] in keyValList, exampleSet))
[{'type': 'type2'}, {'type': 'type2'}, {'type': 'type3'}]
2 of 4
43

Trying a few answers from this post, I tested the performance of each answer.

As my initial guess, the list comprehension is way faster, the filter and list method is second and the pandas is third, by far.

defined variables:

import pandas as pd

exampleSet = [{'type': 'type' + str(number)} for number in range(0, 1_000_000)]

keyValList = ['type21', 'type950000']


1st - list comprehension

%%timeit
expectedResult = [d for d in exampleSet if d['type'] in keyValList]

60.7 ms ± 188 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

2nd - filter and list

%%timeit
expectedResult = list(filter(lambda d: d['type'] in keyValList, exampleSet))

94 ms ± 328 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

3rd - pandas

%%timeit
df = pd.DataFrame(exampleSet)
expectedResult = df[df['type'].isin(keyValList)].to_dict('records')

336 ms ± 1.84 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)


On a side note, using pandas to deal with a dict is not a great idea since the pandas.DataFrame is basically a more memory consuming dict and if you are not going to use a dataframe in the end it is just inefficient.

Find elsewhere
Top answer
1 of 2
18

With list comprehensions:

myDict = [{'first': 'James', 'middle': 'Smith', 'last': 'Joule'}, 
      {'first': 'James', 'middle': 'Johnson', 'last': 'Watt'},
      {'first': 'Christian', 'middle': 'Edward', 'last': 'Doppler'},
      {'first': 'Robert', 'last': 'Antonio'}]

keys = {"middle", "last"}

l = [{k:v for k, v in i.items() if k in keys} for i in myDict]

But you can also use map for this:

myDict = [{'first': 'James', 'middle': 'Smith', 'last': 'Joule'}, 
      {'first': 'James', 'middle': 'Johnson', 'last': 'Watt'},
      {'first': 'Christian', 'middle': 'Edward', 'last': 'Doppler'},
      {'first': 'Robert', 'last': 'Antonio'}]

keys = {"middle", "last"}

l = list(map(lambda x: {k:v for k, v in x.items() if k in keys}, myDict))
print(l)

output:

[{'last': 'Joule', 'middle': 'Smith'}, {'last': 'Watt', 'middle': 'Johnson'}, {'last': 'Doppler', 'middle': 'Edward'}, {'last': 'Antonio'}]
2 of 2
1

Use neverwalkaloner's answer if you are just doing this once. But, if you find yourself manipulating lists of dictionaries often, I've written a free library called PLOD that streamlines much of this.

>>> from PLOD import PLOD
>>> l = PLOD(myDict).dropKey("middle").returnList()
>>> l
[{'last': 'Joule', 'first': 'James'}, {'last': 'Watt', 'first': 'James'}, {'last': 'Doppler', 'first': 'Christian'}, {'last': 'Antonio', 'first': 'Robert'}]
>>> print(PLOD(l).returnString())
[
    {first: 'James'    , last: 'Joule'  },
    {first: 'James'    , last: 'Watt'   },
    {first: 'Christian', last: 'Doppler'},
    {first: 'Robert'   , last: 'Antonio'}
]
>>> 

The library is on PyPi: https://pypi.python.org/pypi/PLOD

To more universally do what you want, I'd need to add a new class method. Perhaps .filterKeys. Perhaps I'll do that in version 1.8. It would then go:

>>> l = PLOD(myDict).filterKeys(['first', 'last']).returnList()

Hmmm...

BTW, the lib supports Python 2.7.x right now. Still working on the 3.5.x release.

🌐
GeeksforGeeks
geeksforgeeks.org › python-filter-dictionary-key-based-on-the-values-in-selective-list
Filter Dictionary Key based on the Values in Selective List - Python - GeeksforGeeks
January 28, 2025 - res[key] = val adds the key-value pair to the result dictionary res if the value is in the list. This method leverages the power of NumPy for efficient filtering. By converting the dictionary values to a NumPy array we can utilize vectorized ...
🌐
LearnPython.com
learnpython.com › blog › filter-dictionary-in-python
How to Filter a Python Dictionary | LearnPython.com
December 26, 2022 - We can apply the same basic logic in order to filter dictionaries in Python. There are only a few differences from the example in the previous section: Instead of elements in a list, we need to iterate over the key-value pairs of the dictionary. We can do this by using the dictionary dict.items() method.
🌐
Finxter
blog.finxter.com › home › learn python blog › how to filter a list of dictionaries in python?
How to Filter a List of Dictionaries in Python? - Be on the Right Side of Change
April 17, 2020 - Here’s the code that shows you how to filter out all user dictionaries that don’t meet the condition of having a key play_time.
🌐
LabEx
labex.io › tutorials › python-how-to-use-list-comprehension-to-filter-keys-in-a-python-dictionary-based-on-their-values-417459
How to use list comprehension to filter keys in a Python dictionary based on their values | LabEx
In this tutorial, we will explore how to leverage Python's list comprehension to filter the keys of a dictionary based on their corresponding values. List comprehension is a concise and powerful way to create new lists in Python, and it can be particularly useful when working with dictionaries. By ...
🌐
Reddit
reddit.com › r/learnpython › how to go about filtering/querying a list of dictionaries?
r/learnpython on Reddit: How to go about filtering/querying a list of dictionaries?
December 26, 2019 -

Given a list of dictionaries like:

[{'first name': 'John', 'last name': 'Smith', 'age': 20, 'sport': 'basketball', 'level': 'college', 'team': 'Bruins', 'team city': 'Los Angeles'}, {'first name': 'Wayne', 'last name': 'Gretsky', 'age': 29, 'sport': 'ice hockey', 'level': 'professional', 'team': 'Kings', 'team city': 'Los Angeles'}, {'first name': 'Dan', 'last name': 'Marino', 'age': 31, 'sport': 'football', 'level': 'professional', 'team': 'Dolphins', 'team city': 'Miami'}...]

Outside of using a SQL query via sqllite module, what would be the best approach of writing a script that returns a smaller list of dictionaries for a different combination of filters (ex. all players with last name of 'Smith', all players under the age of 25, all players with the last name 'Smith' who are under the age of 25, all players in professional teams in Las Vegas, all college baseball players under the age of 21 who are not from Los Angeles, etc.)?

I'm not so much asking for specific code, but what would be your thought process in structuring clean code for such a script?

🌐
GeeksforGeeks
geeksforgeeks.org › python-filter-dictionaries-by-values-in-kth-key-in-list
Python – Filter dictionaries by values in Kth Key in list | GeeksforGeeks
March 31, 2023 - Use map() to apply the lambda function to each dictionary in test_list and store the result in a list. Use filter() to filter the dictionaries in the list based on whether d[K] is in search_list.
🌐
Reddit
reddit.com › r/learnpython › how to filter through a dictionary returning a list of key objects?
r/learnpython on Reddit: How to filter through a dictionary returning a list of key objects?
June 9, 2021 -

So let's say I have a dictionary of

dict = { chevy_01 : "Ford", chevy_02: "Tahoe"}

I want to filter through the KEYS of the dict and get the last two characters of the keys while later performing another function. So I imagine something like this

{for keys in vals print (key[-2:]} 

But I want the end of the function to return a list of the last two characters in the dict so it will just return [01, 02].

I want to do this in a lambda function I'm bad at dict comprehension. Can someone help me out?

🌐
Python Guides
pythonguides.com › python-dictionary-filter
How to Filter a Dictionary in Python
November 10, 2025 - The filter() function returns an iterator, so I converted it back to a dictionary using dict(). This is a neat and efficient way to handle filtering when you prefer a functional style in Python. Sometimes you may want to filter a dictionary by specific keys rather than values.
🌐
Reddit
reddit.com › r/learnpython › how to filter a nested dict by key?
r/learnpython on Reddit: How to filter a nested dict by key?
February 6, 2022 -

I have a nested dictionary of source words, target words, and their frequency counts. It looks like this:

src_tgt_dict = {"each":{"chaque":3}, "in-front-of":{"devant":4}, "next-to":{"à-côté-de":5}, "for":{"pour":7}, "cauliflower":{"chou-fleur":4}, "on":{"sur":2, "panda-et":2}}

I am trying to filter the dictionary so that only key-value pairs that are prepositions remain. To that end, I've written the following:

tgt_preps = set(["devant", "pour", "sur", "à"]) #set of target prepositions

src_tgt_dict = {"each":{"chaque":3}, "in-front-of":{"devant":4}, "next-to":{"à-côté-de":5}, "for":{"pour":7}, "cauliflower":{"chou-fleur":4}, "on":{"sur":2, "panda-et":2}}

new_tgt_preps = [] #list of new target prepositions

for src, d in src_tgt_dict.items(): #loop into the dictionary
    for tgt, count in d.items(): #loop into the nested dictionary
        check_prep = []
        if "-" in tgt: #check to see if hyphen occurs in the target word (this is to capture multi-word prepositions that are not in the original preposition set)
            check_prep.append(tgt[0:(tgt.index("-"))]) #if there's a hyphen, append the preceding word to the check_prep list
            for t in check_prep: 
                if t in tgt_preps: # check to see if the token preceding the hyphen is a preposition
                    new_tgt_preps.append(tgt) #if yes, append the multi-word preposition to the list of new target prepositions

tgt_preps.update(new_tgt_preps) # update the set of prepositions to include the multi-word prepositions

temp_2_src_tgt_dict = {} # create new dict for filtering
for src, d in src_tgt_dict.items(): # loop into the dictionary
    for tgt, count in d.items(): # loop into the nested dictionary
        if tgt in tgt_preps: # if the target is in the set of target prepositions
            temp_2_src_tgt_dict[tgt] = count # add to the new dict with the tgt as the key and the count as the value

When I print the new dict, I get the following:

{'devant': 4, 'pour': 7, 'sur': 2, 'à-côté-de': 5}

And it totally makes sense why I get that, because that's what I told the machine to do. But that's not my intention!

What I want is:

{"in-front-of:{"devant":4}, "for":{"pour":7}, "on":{"sur":2}, {"next-to":{"à-côté-de":5}}

I've tried to instantiate the nested dictionary by writing:

temp_2_src_tgt_dict[tgt][src] = count

but that throws up a Key Error.

Can anyone provide any suggestions or advice? Thank you in advance for your help.

🌐
Finxter
blog.finxter.com › home › learn python blog › how to filter a dictionary in python? (… the most pythonic way)
How to Filter a Dictionary in Python? (... The Most Pythonic Way) - Be on the Right Side of Change
October 9, 2022 - However, by reading this short 8-minute tutorial, you’re going to learn a lot about the nuances of writing Pythonic code. So keep reading! You should always start with the simplest method to solve a problem (see Occam’s razor) because premature optimization is the root of all evil! So let’s have a look at the straightforward loop iteration method to filter a dictionary. ... You want to keep those (key, value) pairs where key meets a certain condition (such as key%2 == 1).