我有一个字典列表,我想删除字典具有相同的键和值对。

这个列表:[{a: 123}, {b: 123}, {a: 123}]

我想返回这个:[{'a': 123}, {'b': 123}]

另一个例子:

这个列表:[{' a ': 123, ' b ': 1234}, {' a ': 3222, ' b ': 1234}, {' a ': 123, ' b ': 1234}]

我想退回这:[{' a ': 123, ' b ': 1234}, {' a ': 3222, ' b ': 1234}]


当前回答

如果您在工作流中使用Pandas,一种选择是直接向pd提供字典列表。DataFrame构造函数。然后使用drop_duplicate和to_dict方法获得所需的结果。

import pandas as pd

d = [{'a': 123, 'b': 1234}, {'a': 3222, 'b': 1234}, {'a': 123, 'b': 1234}]

d_unique = pd.DataFrame(d).drop_duplicates().to_dict('records')

print(d_unique)

[{'a': 123, 'b': 1234}, {'a': 3222, 'b': 1234}]

其他回答

使用自定义键删除重复项:

def remove_duplications(arr, key):
    return list({key(x): x for x in arr}.values())

另一个基于列表推导式的一行代码:

>>> d = [{'a': 123}, {'b': 123}, {'a': 123}]
>>> [i for n, i in enumerate(d) if i not in d[n + 1:]]
[{'b': 123}, {'a': 123}]

在这里,因为我们可以使用字典比较,所以我们只保留初始列表中其余部分中不存在的元素(这个概念只能通过索引n访问,因此使用了enumerate)。

有时老式的循环仍然有用。这段代码比jcollado的稍长,但非常容易阅读:

a = [{'a': 123}, {'b': 123}, {'a': 123}]
b = []
for i in range(len(a)):
    if a[i] not in a[i+1:]:
        b.append(a[i])

不是很短,但很容易读:

list_of_data = [{'a': 123}, {'b': 123}, {'a': 123}]

list_of_data_uniq = []
for data in list_of_data:
    if data not in list_of_data_uniq:
        list_of_data_uniq.append(data)

现在,列表list_of_data_uniq将拥有唯一的字典。

不是一个通用的答案,但如果你的列表恰好是按某个键排序的,像这样:

l=[{'a': {'b': 31}, 't': 1},
   {'a': {'b': 31}, 't': 1},
 {'a': {'b': 145}, 't': 2},
 {'a': {'b': 25231}, 't': 2},
 {'a': {'b': 25231}, 't': 2}, 
 {'a': {'b': 25231}, 't': 2}, 
 {'a': {'b': 112}, 't': 3}]

那么解决方案很简单:

import itertools
result = [a[0] for a in itertools.groupby(l)]

结果:

[{'a': {'b': 31}, 't': 1},
{'a': {'b': 145}, 't': 2},
{'a': {'b': 25231}, 't': 2},
{'a': {'b': 112}, 't': 3}]

使用嵌套字典并(显然)保持顺序。