python从列表中删除重复的字典

时间:2011-08-17 09:42:00

标签: python

我有一个词典列表

l = [
{'firstname': 'joe', 'surname': 'bloggs'},
{'firstname': 'john', 'surname': 'smith'},
{'firstname': 'joe', 'surname': 'bloggs'},
{'firstname': 'jane', 'surname': 'bloggs'}
]

如何删除重复项,即{'firstname': 'joe', 'surname': 'bloggs'}出现两次,以便只显示一次?

2 个答案:

答案 0 :(得分:56)

这样的事情应该做的事情:

result = [dict(tupleized) for tupleized in set(tuple(item.items()) for item in l)]

首先,我在元组列表中转换初始字典,然后将它们放入一个集合(删除重复条目),然后再转换为字典。

答案 1 :(得分:12)

import itertools

import operator

from operator import itemgetter

import pprint

l = [

{'firstname': 'joe', 'surname': 'bloggs'},

{'firstname': 'john', 'surname': 'smith'},

{'firstname': 'joe', 'surname': 'bloggs'},

{'firstname': 'jane', 'surname': 'bloggs'}

]

getvals = operator.itemgetter('firstname', 'surname')

l.sort(key=getvals)

result = []

for k, g in itertools.groupby(l, getvals):

    result.append(g.next())

l[:] = result

pprint.pprint(l)