【问题标题】:finding duplicates in a list of dictionaries [duplicate]在字典列表中查找重复项 [重复]
【发布时间】:2019-01-15 12:16:40
【问题描述】:

我有一个 python 字典列表,可能类似于:

l = [{'id': 'scissor'}, {'id': 'cloth'}, {'id': 'scissor'}]

现在,我想知道是否有一种有效的方法可以从此列表中删除重复项。所以结果应该是这样的:

r = [{'id': 'scissor'}, {'id': 'cloth'}]

我尝试使用frozenset,但无法对字典类型进行哈希处理。有没有一种有效的方法可以从 python 库中的任何结构中执行此操作?

编辑 如果 dict 完全相同,则认为这些项目是重复的。

【问题讨论】:

  • 您要在哪个要求下删除字典?如果他们有相同的钥匙?还是完全一样的?
  • @Bernhard:如果它们与示例中的完全相同。
  • 我们能不能用任何值创建l 的所有元素的hashset。 hashset 的键/元素将给我们r

标签: python


【解决方案1】:

如果你不需要高效:

from functools import partial
import json

list(map(json.loads, set(map(partial(json.dumps, sort_keys=True), l))))

如果你必须要高效:

serialized = map(tuple, map(sorted, map(dict.items, l)))
unique = set(serialized)
result = list(map(dict, unique))

【讨论】:

    【解决方案2】:
    r = [x for i,x in enumerate(l) if x not in l[:i]]
    

    【讨论】:

      【解决方案3】:

      应该工作:

      l2 = []
      
      for d in l:
          if d not in l2:
              l2.append(d)
      

      【讨论】:

      • 不花哨但很简单
      【解决方案4】:

      我建议你以下最简单的方法:

      l = [{'id': 'scissor'}, {'id': 'cloth'}, {'id': 'scissor'}]
      
      r= []
      for i in l:
          if i not in r:
              r.append(i)
      
      print(r)   # [{'id': 'scissor'}, {'id': 'cloth'}]
      

      【讨论】:

        【解决方案5】:

        设置项必须是可散列的,而字典不是。您可以使用pickle 序列化所有dicts,然后使用set 获取唯一项,最后将它们反序列化回dicts:

        import pickle
        print(list(map(pickle.loads, set(map(pickle.dumps, l)))))
        

        这个输出:

        [{'id': 'cloth'}, {'id': 'scissor'}]
        

        【讨论】:

          猜你喜欢
          • 2021-11-17
          • 2022-01-22
          • 2013-02-21
          • 2013-07-06
          • 2021-06-03
          • 2021-09-01
          • 2013-02-12
          • 2019-07-09
          相关资源
          最近更新 更多