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.
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')]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With