【发布时间】:2021-10-11 09:53:34
【问题描述】:
我想删除包含相同“id”值的字典。
字典列表:
example = [{'term': 'potato', 'id': 10}, {'term': 'potatoes', 'id': 10}, {'term': 'apple', 'id': 7}]
期望的输出:
example = [{'term': 'potato', 'id': 10}, {'term': 'apple', 'id': 7}]
目前我只能删除所有重复项,而不是保留一个;或者只删除那些完全相同的字典,而我只是想删除那些具有相同 id 值的字典。
示例代码(尝试):
import ast
new_list = []
seen_keys = set()
for term in example:
d = ast.literal_eval(term) #had to convert a string-dict to a dict first because the dictionaries were transformed to a string in a Solr database
if d['id'] not in seen_keys:
new_list.append(d)
seen_keys.add(d['id'])
【问题讨论】:
标签: python python-3.x list dictionary