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
🌐
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.
Discussions

Filtering Dictionaries by Key and Key/Value
I need to learn how to filter by key/value for several different conditions and then create a new key/value based on the filtered results In general, this will probably involve looping over your keys/values, applying a condition, and creating a new dict from only those items which pass the condition. If your conditions are simple, a dict comprehension is a good way to go. Something like the following, where I create a dict, then filter the keys/value to retain only those items with even-numbered keys: >>> d = dict(enumerate('abcde')) >>> d {0: 'a', 1: 'b', 2: 'c', 3: 'd', 4: 'e'} >>> new_d = {k : v for k, v in d.items() if k % 2 == 0} >>> new_d {0: 'a', 2: 'c', 4: 'e'} For more complex conditions, comprehensions can get long and unwieldy, so vanilla for loops are probably preferred. For example, when filtering keys/values to retain only those items with even-numbered keys AND vowels as values: >>> d = dict(enumerate('abcde')) >>> vowels = 'aeiou' >>> new_d = {} >>> for k, v in d.items(): ... if (v in vowels) and (k % 2 == 0): ... new_d[k] = v ... >>> new_d {0: 'a', 4: 'e'} I need to learn more about dictionaries and how they work to access and calculate the data for my work. I think I understand the basics, but when I get to slightly more complex scenarios I get stuck. To master dicts, spend some time looking at the output of dir(dict) to see which methods are available. Read up on and play around with each because they all have their time and place. Dicts are incredibly useful and powerful when used responsibly. Is there any articles/courses/videos that explain how to use dictionaries in more depth than the basics. If you want an actual article with some example code, these sites generally tend to be quite good in my experience: https://realpython.com/python-dicts/ https://www.programiz.com/python-programming/dictionary https://www.geeksforgeeks.org/python-dictionary/ then perform statistical analysis on them Feel free to ask any stats questions here if they are relevant, though I gather the bulk of your struggles just concern how to use data stored ini dictionaries, not how to do stats with Python. Those are two very different things. More on reddit.com
🌐 r/learnpython
2
2
May 14, 2021
How to filter dictionary by value?
Use dictionary comprehensions. They work pretty much the same as list comprehensions and generator expressions. filtered_dict = {key: value for key, value in old_dict.iteritems() if value > 90} More on reddit.com
🌐 r/learnpython
10
12
December 10, 2013
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
How to filter a nested dict by key?
To be honest I am not sure what some of the middle code is for, so I'm sorry if this is missing some functionality that you need. This takes your src_tgt_dict and tgt_preps and outputs the new_src_tgt_dict you're looking for (again sorry if it's missing in-betweens that you need): 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}} tgt_preps = ["devant", "pour", "sur", "à"] new_tgt_dict = {} for i in src_tgt_dict.items(): for j in tgt_preps: # i[1].keys() is dict_keys([french word]) # list(i[1].keys())[0] returns the word itself # [:len(j)] checks start of string (do you need hyphenation?) if j in list(i[1].keys())[0][:len(j)]: print(i) new_tgt_dict.update({i[0]: i[1]}) More on reddit.com
🌐 r/learnpython
6
2
February 6, 2022
🌐
GitHub
gist.github.com › 89465127 › 5776892
python filter a dictionary by keys or values · GitHub
It's actually not filtering by keys or by values, @Lane012. I think he meant that you can either filter before iterating in for (using filter), or after iterating in for, using the 'if'. ... >>> d = {1:11, 2:22, 3:33} >>> d {1: 11, 2: 22, 3: 33} >>> d.iteritems() Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'dict' object has no attribute 'iteritems' >>>
🌐
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.
🌐
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).
🌐
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 - The condition is given by the if statement. The key value which satisfies this condition is appended to the new list with the help of append function. Next, the new list is printed. Lastly, we are converting the list to a dictionary and printing the filtered dictionary.
Find elsewhere
🌐
AskPython
askpython.com › python › dictionary › filter-dictionary-string-values
Filter Dictionary Using String Values in Python - AskPython
May 23, 2023 - In this way, we can access the value of any key if we define that key with the dictionary name inside the ‘[ ]’ brackets. The filter () function in Python is used for filtering the dictionaries.
🌐
YouTube
youtube.com › watch
How to Filter a Dictionary in Python? - YouTube
Given a dictionary and a filter condition. How to filter a dictionary by … … key so that only those (key, value) pairs in the dictionary remain where the ...
Published   May 23, 2020
🌐
w3resource
w3resource.com › python-exercises › dictionary › python-data-type-dictionary-exercise-42.php
Python: Filter a dictionary based on values - w3resource
June 28, 2025 - Write a Python program to filter a dictionary and return only those entries where the value exceeds a given threshold. Write a Python program to use a lambda function in dictionary comprehension to keep only key-value pairs satisfying a condition. Write a Python program to create a new dictionary by removing entries whose values do not meet a specified predicate.
🌐
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.
🌐
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
July 22, 2020 - This approach uses the built-in filter() function combined with dictionary comprehension for a more functional programming style ? # Original dictionary dictA = {'Mon': 'Phy', 'Tue': 'chem', 'Wed': 'Math', 'Thu': 'Bio'} key_list = ['Tue', 'Thu'] print("Given Dictionary:") print(dictA) print("Keys for filter:") print(key_list) # Using filter() function filtered_keys = filter(lambda x: x in dictA, key_list) filtered_dict = {key: dictA[key] for key in filtered_keys} print("Filtered dictionary:") print(filtered_dict)
🌐
Reddit
reddit.com › r/learnpython › filtering dictionaries by key and key/value
Filtering Dictionaries by Key and Key/Value : r/learnpython
May 14, 2021 - If your conditions are simple, a dict comprehension is a good way to go. Something like the following, where I create a dict, then filter the keys/value to retain only those items with even-numbered keys:
🌐
Kite
kite.com › python › answers › how-to-filter-a-dictionary-by-key-in-python
Kite is saying farewell - Code Faster with Kite
November 20, 2022 - P.S. Most of our code has been open sourced on Github here. It includes our data-driven Python type inference engine, Python public-package analyzer, desktop software, editor integrations, Github crawler and analyzer, and much more.
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-filter-dictionary-key-based-on-the-values-in-selective-list
Filter Dictionary Key based on the Values in Selective List - Python - GeeksforGeeks
July 11, 2025 - zip(d.keys(), values) combines the keys and values into pairs and the dictionary comprehension is used to filter out those that are not in 'li'
🌐
YouTube
youtube.com › watch
Python : Filtering Dictionary Keys by Value - YouTube
Video 124: In this tutorial, we delve into the task of filtering dictionary keys by value.We are given a dictionary of key:value pairs and the value the user...
Published   March 17, 2024
Top answer
1 of 4
239

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
45

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.

🌐
Linux find Examples
queirozf.com › entries › python-dict-examples
Python Dict Examples
December 27, 2023 - allowed_values = [1, 2] d = {'foo':1, ... => {val}") # >>> foo => 10 # >>> bar => 30 # >>> baz => 20 · To order dict elements by key, turn them into an ordered list of tuples:...
🌐
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.