Reputation:
dictss = [{'country': 'USA'},
{'country': 'USA'},
{'name': 'stuart',
'country': 'USA'},
{'name': 'tom',
'country': 'USA'}]
If key name
is not there then have to remove the dicts which does have the key name
expected output:
[{'name': 'stuart',
'country': 'USA'},
{'name': 'tom',
'country': 'USA'}]
Upvotes: 1
Views: 46
Reputation: 27577
Simply use a list comprehension with a filter of if 'name' in d.keys()
:
dictss = [d for d in dictss if 'name' in d.keys()]
print(dictss)
Output:
[{'name': 'stuart', 'country': 'USA'}, {'name': 'tom', 'country': 'USA'}]
Upvotes: 1
Reputation: 11949
You could just consider the dictionaries that have name
as a key using a list comprehension
>>> res = [d for d in dictss if 'name' in d]
>>> res
[{'name': 'stuart', 'country': 'USA'}, {'name': 'tom', 'country': 'USA'}]
Upvotes: 1