【问题标题】:Remove duplicates from the list of dictionaries (with a unique value)从字典列表中删除重复项(具有唯一值)
【发布时间】:2016-06-08 14:48:41
【问题描述】:

我有一个字典列表,每个字典都描述了一个文件(文件格式、文件名、文件大小……以及文件的完整路径 [始终唯一])。目标是排除描述同一文件副本的除一个字典以外的所有字典(我只希望每个文件有一个字典(条目),无论有多少副本。

换句话说:如果 2 个(或更多)dicts 仅在一个键(即路径)上有所不同 - 只留下其中一个)。

例如,这里是源列表:

src_list = [{'filename': 'abc', 'filetype': '.txt', ... 'path': 'C:/'},
            {'filename': 'abc', 'filetype': '.txt', ... 'path': 'C:/mydir'},
            {'filename': 'def', 'filetype': '.zip', ... 'path': 'C:/'},
            {'filename': 'def', 'filetype': '.zip', ... 'path': 'C:/mydir2'}]

结果应该是这样的:

dst_list = [{'filename': 'abc', 'filetype': '.txt', ... 'path': 'C:/'},
            {'filename': 'def', 'filetype': '.zip', ... 'path': 'C:/mydir2'}]

【问题讨论】:

  • 标记问题的复制。查看接受的答案并使用x['key1'] in seen or seen_add(x['key1']) 解决您的问题
  • 为什么会被丢弃? {'key1': 'non_unique_value2', 'key2': 'unique_value3'}
  • 键和值的元组应该添加到seen,而不是单独的值。
  • @Suzana_K,你为什么这么认为?
  • 我想你会在你的问题上找到答案Here

标签: python list python-3.x dictionary python-2.x


【解决方案1】:

使用另一个字典将列表中的字典映射到实际字典中的“忽略”键。这样,将只保留每种类型中的一种。当然,dicts 是不可散列的,所以你必须使用(排序的)元组来代替。

src_list = [{'filename': 'abc', 'filetype': '.txt', 'path': 'C:/'},
            {'filename': 'abc', 'filetype': '.txt', 'path': 'C:/mydir'},
            {'filename': 'def', 'filetype': '.zip', 'path': 'C:/'},
            {'filename': 'def', 'filetype': '.zip', 'path': 'C:/mydir2'}]
ignored_keys = ["path"]
filtered = {tuple((k, d[k]) for k in sorted(d) if k not in ignored_keys): d for d in src_list}
dst_lst = list(filtered.values())

结果是:

[{'path': 'C:/mydir', 'filetype': '.txt', 'filename': 'abc'}, 
 {'path': 'C:/mydir2', 'filetype': '.zip', 'filename': 'def'}]

【讨论】:

    【解决方案2】:

    我自己的解决方案(也许不是最好的,但确实有效):

        dst_list = []
        seen_items = set()
        for dictionary in src_list:
            # here we cut the unique key (path) out to add it back later after a duplicate check
            path = dictionary.pop('path', None)
            t = tuple(dictionary.items())
            if t not in seen_items:
                seen_items.add(t)
                # duplicate-check passed, adding the unique key back to it's dictionry
                dictionary['path'] = path
                dst_list.append(dictionary)
    
        print(dst_list) 
    

    在哪里

    src_list 是可能重复的原始列表,

    dst_list是最终的无重复列表,

    path 是唯一键

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-02-16
      • 1970-01-01
      • 2016-03-13
      • 2016-03-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多