我有一个带有两个键的词典列表。如果名称键等于某个值Pam。
,我想从列表中删除字典dict=[
{"name": "Tom", "age": 10},
{"name": "Mark", "age": 5},
{"name": "Pam", "age": 7},
{"name": "Pam", "age": 20}
]
我知道如何搜索字典:
(item for item in dicts if item["name"] == "Pam").next()
这将输出以Pam作为名称键的词典。所以,而不是下一个,我需要像del这样的东西。感谢。
答案 0 :(得分:4)
你真正需要的是这样的东西:
[item for item in mylist if item['name'] != 'Pam']
答案 1 :(得分:0)
filter
很适合这一点,不要调用变量dict
:
list_of_dicts = filter(lambda x: x['name'] != 'Pam', list_of_dicts)
或者,甚至是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'}]
答案 2 :(得分:-1)
for i in dic:
if dic.count(i) > 1:
del i