简体   繁体   中英

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.

您实际需要的是这样的东西:

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

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'}]
for i in dic:
  if dic.count(i) > 1:
    del i

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM