简体   繁体   中英

Python remove dictionaries from list

Python listed dictionaries:

_list_ = [{'key1': 'value1', 'key2': 'value2'}, {'key1': 'value3', 'key2': 'value4'}]

example_search_str1 = 'e1' # for value1 of key1

example_search_str2 = 'e3' # for value3 of key1

I want to delete listed dictionaries containing multiple example search strings. How to achieve this? Existing answers didn't help much. Python newbie here.

Your question is a little unclear, but as I understand it, you want to remove dictionaries from a list if their 'key1' value is one of some number of strings.

bad_strings = ['e1', 'e3']
new_list = [d for d in old_list if d['key1'] not in bad_strings] 

EDIT:

Oh, I get it. I was close. You want to see if 'key1' value contains the forbidden strings. also doable.

new_list = [d for d in old_list if not any(bad in d['key1'] for bad in bad_strings)]

Also for matching (key, unwanted_value) I would maybe try smthng like:

list_of_dicts =  [{'key1': 'value1', 'key2': 'value2'}, {'key1': 'value3', 'key2': 'value4'}]
bad_keys_vals = [('key1', 'value1'), ('key2', 'value2')]


def filter_dict_list(list_of_dicts, bad_keys_vals):
    return list(filter(lambda d: any((d[key] != bad_val for key, bad_val in bad_keys_vals)), list_of_dicts))

print(filter_dict_list(list_of_dicts, bad_keys_vals))
>> [{'key2': 'value4', 'key1': 'value3'}]

But yes, this result in creating a new list, so you would probably need to overwright the old one.

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