Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/290.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在Python中按值删除字典项列表中的重复字典项_Python_Dictionary - Fatal编程技术网

如何在Python中按值删除字典项列表中的重复字典项

如何在Python中按值删除字典项列表中的重复字典项,python,dictionary,Python,Dictionary,我有一个大约5000个字典条目的列表,如下所示: list_of_dicts = [ {'organization_name': 'OrgA', 'country': 'United States'}, {'organization_name': 'OrgA', 'country': None }, {'organization_name': 'OrgB', 'country': 'Finland'}, {'organization_name': 'OrgC', 'country': 'Uni

我有一个大约5000个字典条目的列表,如下所示:

list_of_dicts = [

{'organization_name': 'OrgA', 'country': 'United States'},
{'organization_name': 'OrgA', 'country': None },
{'organization_name': 'OrgB', 'country': 'Finland'},
{'organization_name': 'OrgC', 'country': 'United States'}

]
我想从此列表中删除重复的词典项。我所说的重复项是指对“组织名称”具有相同值的项。例如,第一个和第二个项目是重复的,但第一个和第四个项目不是重复的


实现这一目标的好方法是什么?请注意,这是一个一次性的数据清理练习,因此解决方案不必非常高效。

您可以使用一个集合来跟踪您看到的组织,并且只有在您以前没有看到的情况下才保留dict:

orgs = set()
kept_dicts = []
for d in list_of_dicts:
    org = d['organization_name']
    if org not in orgs:
        kept_dicts.append(d)
        orgs.add(org)

你是想两个都放弃还是保留一个?说得好。我想保留1。因此,如果同一项有10个实例,我只希望列表中保留1个,这非常有效。非常感谢。