Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python filter list of dictionaries based on key value

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 dictionaries but only the ones of a certain "type". I think i'm just really struggling with list/dictionary comprehensions.

so an example list would look like:

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

i have a list of key values. lets say for example:

keyValList = ['type2','type3'] 

where the expected resulting list would look like:

expectedResult = [{'type':'type2'},{'type':'type2'},{'type':'type3'}] 

I know i could do this with a set of for loops. I know there has to be a simpler way though. i found a lot of different flavors of this question but none that really fit the bill and answered the question. I would post an attempt at the answer... but they weren't that impressive. probably best to leave it open ended. any assistance would be greatly appreciated.

like image 313
m25 Avatar asked Mar 14 '15 16:03

m25


People also ask

How do you sort a list of dictionaries in Python based on a key?

To sort a list of dictionaries according to the value of the specific key, specify the key parameter of the sort() method or the sorted() function. By specifying a function to be applied to each element of the list, it is sorted according to the result of that function.

How do you filter a dictionary list in Python?

We can easily search a list of dictionaries for an item by using the filter() function with a lambda function. In Python3, the filter() function returns an object of the filter class. We can convert that object into a list with the list() function.

Can a value of Key in dictionary Python be a list?

A Python dictionary is a collection of key-value pairs where each key is associated with a value. A value in the key-value pair can be a number, a string, a list, a tuple, or even another dictionary. In fact, you can use a value of any valid type in Python as the value in the key-value pair.

Can you filter dictionaries in Python?

Filter a Dictionary by values in Python using filter() filter() function iterates above all the elements in passed dict and filter elements based on condition passed as callback.


1 Answers

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'}] 
like image 71
Bhargav Rao Avatar answered Sep 30 '22 13:09

Bhargav Rao