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 elements in elements of alist Python

I have a list that looks like that:

[{'ip': 'x.x.x.x',
  'error': True,
  'reason': 'Reserved IP Address',
  'reserved': True,
  'version': 'IPv4'},
 {'ip': 'x.x.x.x',
  'error': True,
  'reason': 'Reserved IP Address',
  'reserved': True,
  'version': 'IPv4'},
 {'ip': 'x.x.x.x',
  'version': 'IPv4',
  'city': 'Munich',
  'region': 'Bavaria',
  'country': 'DE',
  'country_name': 'Germany',
  'country_code': 'DE',
  'country_code_iso3': 'DEU',
  'country_capital': 'Berlin'},
 {'ip': 'x.x.x.x',
  'version': 'IPv4',
  'city': 'Düsseldorf',
  'region': 'North Rhine-Westphalia',
  'country': 'DE',
  'country_name': 'Germany',
  'country_code': 'DE',
  'country_code_iso3': 'DEU',
  'country_capital': 'Berlin'}]

What I need is a way to remove that elements than have an "error" or "reason : ‘Reserved IP Address’" element inside and get only the elements that have complete data. Like this:

#Removing unnecesary elements
[{'ip': 'x.x.x.x',
  'version': 'IPv4',
  'city': 'Munich',
  'region': 'Bavaria',
  'country': 'DE',
  'country_name': 'Germany',
  'country_code': 'DE',
  'country_code_iso3': 'DEU',
  'country_capital': 'Berlin'},
 {'ip': 'x.x.x.x',
  'version': 'IPv4',
  'city': 'Düsseldorf',
  'region': 'North Rhine-Westphalia',
  'country': 'DE',
  'country_name': 'Germany',
  'country_code': 'DE',
  'country_code_iso3': 'DEU',
  'country_capital': 'Berlin'}]

Is there any way to do that?

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

>Solution :

Try with list comprehension:

>>> [d for d in mylist if not d.get("error") and d.get("reason")!="Reserved IP Address"]
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