'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?
Solution 1:[1]
Another possible approach using the filter method, might be more flexible for more complex conditions
list_of_dict = [{'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'}]
def contains_error(dictionary):
return ('error' or 'reason') not in dictionary
result = list(filter(contains_error, list_of_dict))
print(result)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
