Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter a list of dictionaries based on key (not key value) in Python

I would like to filter a list of (different) dictionaries based on a single key, not the value this key holds.

This is an example:

diclist_example = [{'animal': 'dog', 'legs': 'four'}, 
                   {'tvshow': 'Game of Thrones','rating': 'good'},
                   {'food': 'banana','color': 'yellow'},
                   {'animal': 'sheep', 'legs': 'four'}, 
                   {'tvshow': 'Gossip Girl','rating': 'bad'},
                   {'food': 'pizza','color': 'red-ish'}]

The problem with this is when I try to work with the 'animal' values for example, I get a KeyError because some dictonaries do not contain the 'animal' value.

I would like to generate a new list of dictionaries, containing all the dictionaries based on a key, for example, a list with all the animals, a list with all the tvshows of a list with all the foods.

like image 308
John T. Avatar asked Dec 10 '25 02:12

John T.


1 Answers

You can do it with a lambda function that filter elements with a list comprehension. This function will return a list of all identical elements

diclist_example = [{'animal': 'dog', 'legs': 'four'}, 
                   {'tvshow': 'Game of Thrones', 'rating': 'good'},
                   {'food': 'banana','color': 'yellow'},
                   {'animal': 'sheep', 'legs': 'four'}, 
                   {'tvshow': 'Gossip Girl', 'rating': 'bad'},
                   {'food': 'pizza', 'color': 'red-ish'}]

getAllElementsWithSameKey = lambda key: [d for d in diclist_example if key in d]
getAllElementsWithSameKey('animal')

You can create a list of all your dictionaries with

allElements = [getAllElementsWithSameKey(k) for k in ('animal','tvshow','food')]
like image 178
Guillaume Jacquenot Avatar answered Dec 11 '25 16:12

Guillaume Jacquenot



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!