首页 > 解决方案 > 如何删除包含列表的字典列表中的重复项?

问题描述

我有一个字典列表,其中每个字典本身都有一个列表:

    [{'author': 'Stephen King', 'books': ['The stand', 'The 
    Outsider']}, {'author': 'Ernest Hemingway', 'books': ['A 
    Moveable Feast', 'The sun Also Rises']},{'author': 'Stephen 
    King', 'books': ['The stand', 'The Outsider']}]

我已经尝试了大多数方法来删除字典列表中的重复项,到目前为止,由于字典中的数组,它们似乎不起作用。

目的是删除字典列表中的重复项,其中每个字典本身都有一个列表

上述数据中的预期输出应该是:

    [{'author': 'Stephen King', 'books': ['The stand', 'The 
    Outsider']}, {'author': 'Ernest Hemingway', 'books': ['A 
    Moveable Feast', 'The sun Also Rises']}]

标签: arrayspython-3.xdictionaryduplicates

解决方案


您应该编写一些代码,可以将您格式中的字典转换为可散列对象。然后正常的重复数据删除代码(使用 a set)将起作用:

data = [{'author': 'Stephen King', 'books': ['The stand', 'The Outsider']},
        {'author': 'Ernest Hemingway', 'books': ['A Moveable Feast', 'The sun Also Rises']},
        {'author': 'Stephen King', 'books': ['The stand', 'The Outsider']}]

seen = set()
result = []
for dct in data:
    t = (dct['author'], tuple(dct['books'])) # transform into something hashable
    if t not in seen:
        seen.add(t)
        result.append(dct)

此代码假定您的字典只有键'author'and 'books',没有别的。如果您想更通用一点并支持其他键和值,您可以稍微扩展逻辑。这是一种替代计算t,它将支持任意键(只要它们都是可比较的)和值中的任意数量的列表:

t = tuple((k, tuple(v) if insinstance(v, list) else v) for k, v in sorted(dct.items())

推荐阅读