Twilight0 Twilight0 - 1 year ago 126
Python Question

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.

Answer Source

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] 


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)]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download