Python – remove one dictionary by key:value related to other value from list of dicts

Question:

I have list of dictionaries like below:

my_dict = [{'name': 'weather', 'result': 'good'}, {'name': 'weather', 'result': 'bad'}, {'name': 'weather', 'result': 'average'}, {'name': 'wind', 'result': 'strong'}, {'name': 'water', 'result': 'high'}]

As you can see all dictionaries have the same key pairs (‘name’ and ‘result’) but different values. I’d like to keep all dictionaries except the ones with ‘name’: ‘weather’ and ‘result’ != ‘good’

Result should look like:

my_dict = [{'name': 'weather', 'result': 'good'}, {'name': 'wind', 'result': 'strong'}, {'name': 'water', 'result': 'high'}]

I can do it by naive method – but is there a more sophisticated method like comprehension or filter?

Asked By: Kjurczak

||

Answers:

This does the trick:

a = [d for d in my_dict if not (d['name'] == 'weather' and d['result'] != 'good')]

For each element in the array (a dictionary) select it if the name is ‘weather’ and the the result is anything but ‘good’.

This is a particular good candidate for a comprehension.

Answered By: Jaco Van Niekerk
new_dicts = [
    d for d in my_dicts 
    if not (d.get('name') == 'weather' and d.get('result') != 'good')
]

Has the benefit of gracefully handling situations where for some reason the expected keys (weather and/or result) are missing. dict.get() returns None by default, if the key is missing. Accessing the value by key directly with __getitem__ (the []-notation) throws a KeyError, when the key is missing.

Answered By: Daniil Fajnberg

A method that uses filter is as below:

list(filter(lambda x: not (x['name'] == 'weather' and x['result'] != 'good'), my_dict))

Result:

[{'name': 'weather', 'result': 'good'},
 {'name': 'wind', 'result': 'strong'},
 {'name': 'water', 'result': 'high'}]
Answered By: J. Choi

At this point it’s a bit redundant with all the other answers but here’s another syntax:

new_dict = [d for d in my_dict if d['name'] != 'weather' or d['result'] == 'good']

And the result:

[{'name': 'weather', 'result': 'good'},
 {'name': 'wind', 'result': 'strong'},
 {'name': 'water', 'result': 'high'}]
Answered By: Diurnambule