简体   繁体   中英

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

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?

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.

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.

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'}]

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'}]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM