Reputation: 1542
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
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
Reputation: 48028
What you actually need is something like this:
[item for item in mylist if item['name'] != 'Pam']
Upvotes: 4