I have a list of dictionaries:
my_dicts = [
{'name': 'aaa',
'codename': 'bbbb',
'type': 'cccc',
'website': 'url1'},
{'name': 'aaa2',
'codename': 'bbbb2',
'type': 'cccc2',
'product_url': 'url2'},
{'name': 'aaa2',
'codename': 'bbbb2',
'type': 'cccc2',
'dop_url': 'url3'}
]
and a list:
my_list = ['url1', 'url3']
My goal is to have this output:
my_dicts = [
{'name': 'aaa2',
'codename': 'bbbb2',
'type': 'cccc2',
'product_url': 'url2'}
]
I want to find the most efficient way to remove the dictionaries where any value of said dictionary is in a list.
I tried this, but I’m getting the following error: RuntimeError: dictionary changed size during iteration.
for url in my_list:
for e in my_dicts:
for key, value in e.items():
if value == url:
del e[key]
>Solution :
You can use a list comprehension with all(), retaining only the dictionaries that do not have a key-value pair where the value appears in my_list:
[item for item in my_dict if all(url not in item.values() for url in my_list)]
This outputs:
[{'name': 'aaa2', 'codename': 'bbbb2', 'type': 'cccc2', 'product_url': 'url2'}]