Skip to content

Instantly share code, notes, and snippets.

@sweldon
Last active October 25, 2023 19:17
Show Gist options
  • Save sweldon/3c64c65079f06ba12dfbf0c7a588972e to your computer and use it in GitHub Desktop.
Save sweldon/3c64c65079f06ba12dfbf0c7a588972e to your computer and use it in GitHub Desktop.
Filter list of dictionaries
# Filter a list of dicts by a dynamic number of conditions (which is a dict of key/vals)
# If you pass a list as a filter value, it will be treated as an OR condition
list_of_dicts = [{"name": "Steve", "age": 29}, {"name": "John", "age": 99}]
filter_conditions = {"name": "Steve", "age": [18, 29]} # Would return 1 result
filtered_records = list(filter(
lambda record: all((
# If the value is a list, filter for any values in that list (i.e. OR condition)
record[filter_key] in filter_value
if isinstance(filter_value, list)
# Otherwise, filter by the exact value
else record[filter_key] == filter_value
for (filter_key, filter_value)
in filter_conditions.items()
)),
list_of_dicts
))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment