Koba
Koba

Reputation: 1542

Delete dictionary from a list of dictionary if its key equals certain value

I have a list of dictionaries with two keys. I want to remove a dictionary from the list if its name key equals a certain value,Pam.

dict=[
{"name": "Tom", "age": 10},
{"name": "Mark", "age": 5},
{"name": "Pam", "age": 7},
{"name": "Pam", "age": 20}
]

I know how to search through the dictionary:

(item for item in dicts if item["name"] == "Pam").next()

This will output the dictionaries that have Pam as the name key. So, instead of next I need something like del. Thanks.

Upvotes: 0

Views: 271

Answers (3)

majno
majno

Reputation: 9

for i in dic:
  if dic.count(i) > 1:
    del i

Upvotes: -1

Burhan Khalid
Burhan Khalid

Reputation: 174708

filter is a good use for this, and don't call your variable dict:

list_of_dicts = filter(lambda x: x['name'] != 'Pam', list_of_dicts)

Or, even ifilterfalse, from itertools:

>>> import itertools
>>> i = [
... {"name": "Tom", "age": 10},
... {"name": "Mark", "age": 5},
... {"name": "Pam", "age": 7},
... {"name": "Pam", "age": 20}
... ]
>>> list(itertools.ifilterfalse(lambda x: x['name'] == 'Pam', i))
[{'age': 10, 'name': 'Tom'}, {'age': 5, 'name': 'Mark'}]
>>> i = list(itertools.ifilterfalse(lambda x: x['name'] == 'Pam', i))
>>> i
[{'age': 10, 'name': 'Tom'}, {'age': 5, 'name': 'Mark'}]

Upvotes: 0

g.d.d.c
g.d.d.c

Reputation: 48028

What you actually need is something like this:

[item for item in mylist if item['name'] != 'Pam']

Upvotes: 4

Related Questions