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'}]
Answer from Bhargav Rao on Stack Overflow
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.

🌐
GeeksforGeeks
geeksforgeeks.org › python › filter-list-of-dictionaries
Filter List Of Dictionaries in Python - GeeksforGeeks
July 23, 2025 - In this example, below code filters a list of dictionaries (`original_list`) using the `filter()` function and a lambda expression to include only dictionaries where the 'age' key is greater than 25.
Discussions

How to go about filtering/querying a list of dictionaries?
[x for x in dict_list if x[“last_name”] == “Smith”] Assuming your list of dicts is dict_list More on reddit.com
🌐 r/learnpython
27
98
December 26, 2019
How to filter dictionary keys by substring in Python? - Ask a Question - TestMu AI (formerly LambdaTest) Community
How can I filter items in a Python dictionary where the keys contain a specific substring? I’m a C programmer transitioning to Python, and I’m familiar with how this can be done in C. In C, I would iterate over the dictionary (or hash map) and check if the key contains a specific substring. More on community.testmuai.com
🌐 community.testmuai.com
0
December 25, 2024
Filter a list of dicts
Add a "when: item.type = server" just before the loop line, same indent as the loop. This means it does the loop first, but will only do the include when the conditional matches. More info here: https://docs.ansible.com/ansible/latest/user_guide/playbooks_conditionals.html#conditionals-with-includes More on reddit.com
🌐 r/ansible
12
3
May 31, 2022
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
🌐
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 - Coming to filtering the dictionary based on the key values, we have seen three approaches. Firstly, we created a list of dictionaries according to the syntax and used list comprehension to set a condition and print the filtered list of dictionaries that satisfy the given condition.
🌐
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-list-of-dictionaries-based-on-key-values-in-python
Filter List of Dictionaries Based on Key Values in Python - GeeksforGeeks
July 23, 2025 - ... p = [{'name': 'geek1', 'role': ... the dictionaries def fun(d): return d['role'] in f # Use filter() with the filter_func function res = list(filter(fun, p)) print(res) ......
🌐
LearnPython.com
learnpython.com › blog › filter-dictionary-in-python
How to Filter a Python Dictionary | LearnPython.com
December 26, 2022 - The result list contains only the non-negative numbers of the original list. A more advanced method for filtering Python lists is to use a list comprehension. Read this article on list comprehensions to learn more about it! We can apply the same basic logic in order to filter dictionaries in Python.
Find elsewhere
🌐
GeeksforGeeks
geeksforgeeks.org › python › filter-list-of-python-dictionaries-by-key-in-python
Filter List of Python Dictionaries by Key in Python - GeeksforGeeks
July 23, 2025 - After applying map(), we filter out None values with a list comprehension. for loop in Python is a more traditional approach to filter dictionaries by key.
🌐
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
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)
🌐
Untitled Publication
rodny.hashnode.dev › understanding-lists-of-dictionaries-in-python
Understanding Lists of Dictionaries in Python
September 21, 2024 - Each dictionary holds the information of a single user, such as their name and age. ... You can use loops or list comprehensions to filter dictionaries in the list based on specific conditions.
🌐
Python documentation
docs.python.org › 3 › reference › expressions.html
6. Expressions — Python 3.14.6 documentation
Atoms are the most basic elements of expressions. The simplest atoms are names or literals. Forms enclosed in parentheses, brackets or braces are also categorized syntactically as atoms. ... atom: | 'True' | 'False' | 'None' | '...' | identifier | literal | enclosure enclosure: | parenth_form | list_display | dict_display | set_display | generator_expression | yield_atom
🌐
Medium
medium.com › @carpioaltheadianne05 › utilizing-python-lists-of-dictionaries-for-data-management-real-life-applications-and-best-27ee3f4122fc
Utilizing Python Lists of Dictionaries for Data Management: Real-Life Applications and Best Practices | by Althea Carpio | Medium
October 1, 2024 - The same fundamental reasoning can be used to filter dictionaries in Python. The example from the preceding section differs in only a few ways: Instead of elements in a list, we need to iterate over the key-value pairs of the dictionary.
🌐
Python documentation
docs.python.org › 3 › howto › sorting.html
Sorting Techniques — Python 3.14.6 documentation
Author, Andrew Dalke and Raymond Hettinger,. Python lists have a built-in list.sort() method that modifies the list in-place. There is also a sorted() built-in function that builds a new sorted lis...
🌐
Claude Platform Docs
platform.claude.com › docs › en › build-with-claude › prompt-engineering › claude-prompting-best-practices
Prompting best practices - Claude Platform Docs
2 weeks ago - client = anthropic.Anthropic() message = client.messages.create( model="claude-opus-4-8", max_tokens=1024, system="You are a helpful coding assistant specializing in Python.", messages=[ {"role": "user", "content": "How do I sort a list of dictionaries by key?"} ], ) print(message.content)
🌐
TestMu AI
community.testmuai.com › ask a question
How to filter dictionary keys by substring in Python? - Ask a Question - TestMu AI (formerly LambdaTest) Community
December 25, 2024 - How can I filter items in a Python dictionary where the keys contain a specific substring? I’m a C programmer transitioning to Python, and I’m familiar with how this can be done in C. In C, I would iterate over the dictionary (or hash map) and check if the key contains a specific substring.
🌐
Django REST framework
django-rest-framework.org › api-guide › requests
Requests - Django REST framework
request.stream returns a stream representing the content of the request body. You won't typically need to directly access the request's content, as you'll normally rely on REST framework's default request parsing behavior. As REST framework's Request extends Django's HttpRequest, all the other standard attributes and methods are also available. For example the request.META and request.session dictionaries are available as normal.
🌐
Vultr Docs
docs.vultr.com › python › built-in › filter
Python filter() - Filter Collection Items | Vultr Docs
November 22, 2024 - Python's filter() function is a versatile tool for filtering elements in a collection based on specific test functions. Whether dealing with lists, tuples, or dictionaries, filter() can significantly streamline the process of data extraction ...
🌐
w3resource
w3resource.com › python-exercises › dictionary › python-data-type-dictionary-exercise-42.php
Python: Filter a dictionary based on values - w3resource
June 28, 2025 - # Iterate through the key-value pairs in 'marks' and include them in the new dictionary if the value is greater than or equal to 170. result = {key: value for (key, value) in marks.items() if value >= 170} # Print the new dictionary containing only the filtered key-value pairs. print(result) ... Original Dictionary: {'Cierra Vega': 175, 'Alden Cantrell': 180, 'Kierra Gentry': 165, 'Pierre Cox': 190} Marks greater than 170: {'Cierra Vega': 175, 'Alden Cantrell': 180, 'Pierre Cox': 190} ... Write a Python program to filter a dictionary and return only those entries where the value exceeds a given threshold.
🌐
Alphafoldserver
alphafoldserver.com
AlphaFold Server
AlphaFold Server – powered by AlphaFold 3 – provides accurate structure predictions for how proteins interact with other molecules, like DNA, RNA and more.
🌐
Coursera
coursera.org › courses
Best Python Courses & Certificates [2026] | Coursera
Typical topics covered in Python courses include basic syntax, data structures (like lists and dictionaries), control flow (if statements, loops), functions, and modules. Advanced courses may explore object-oriented programming, web development frameworks, data analysis libraries, and machine learning techniques. This comprehensive curriculum ensures you gain a well-rounded understanding of ...
🌐
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
You can also use list comprehension to filter dictionaries based on multiple conditions. For example, let's say you have a list of dictionaries representing student information, and you want to extract the names of students who scored above 90 and are in the age range of 18-22.