Home > other >  Remove elements in elements of alist Python
Remove elements in elements of alist Python

Time:02-17

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?

CodePudding user response:

Try with list comprehension:

>>> [d for d in mylist if not d.get("error") and d.get("reason")!="Reserved IP Address"]
  • Related