Skip to content

Python filter list of dictionaries

  • by

You can use the list comprehension or filter function to filter the list of dictionaries in Python. You could also use a for loop to filter a list of dictionaries.

Python filter list of dictionaries example

Simple example code Filter list of dictionaries using list comprehension

dictlist = [{'first': 'James', 'last': 'Joule'},
{'first': 'James', 'last': 'Watt'},
{'first': 'Christian', 'last': 'Doppler'}]

res = [x for x in dictlist if x['first'] == 'Christian']
print(res)

sres = [x['last'] for x in dictlist if x['first'] == 'Christian']
print(sres)

Output:

Python filter list of dictionaries

Filter list of dictionaries based on key value

Using list comprehension

exampleSet = [{'type': 'type1'}, {'type': 'type2'}, {'type': 'type4'}, {'type': 'type3'}]
keyValList = ['type2', 'type3']

res = [d for d in exampleSet if d['type'] in keyValList]
print(res)

Another way is by using filter

list(filter(lambda d: d['type'] in keyValList, exampleSet))

Output: [{‘type’: ‘type2’}, {‘type’: ‘type3’}]

Lambda filters a list of dictionaries Python

ages = [{'employedId': 1, 'age': 22},
{'employedId': 2, 'age': 32},
{'employedId': 3, 'age': 17},
{'employedId': 4, 'age': 53},
{'employedId': 5, 'age': 32},
{'employedId': 6, 'age': 22}
]
list_filtred = list(filter(lambda tag: tag['age'] == 22, ages))

print(list_filtred)

Output: [{’employedId’: 1, ‘age’: 22}, {’employedId’: 6, ‘age’: 22}]

Do comment if you have any doubts or suggestions on this Python filter topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.