Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Remove dictionary from list if it contains forbidden value

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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'}]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading