user12942323
user12942323

Reputation:

If key is not there remove those dicts in a list

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

Answers (3)

dimay
dimay

Reputation: 2804

Try it:

[i for i in dictss if "name" in i]

Upvotes: 0

Red
Red

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

abc
abc

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

Related Questions