【问题标题】:Remove duplicates key from list of dictionaries python从字典python列表中删除重复键
【发布时间】:2022-04-14 01:04:11
【问题描述】:

我正在尝试从以下列表中删除重复项:

distinct_cur = [
    {'rtc': 0, 'vf': 0, 'mtc': 0, 'doc': 'good job', 'foc': 195, 'st': 0.0, 'htc': 2, '_id': ObjectId('58e86a550a0aeff4e14ca6bb'), 'ftc': 0}, 
    {'rtc': 0, 'vf': 0, 'mtc': 0, 'doc': 'good job', 'foc': 454, 'st': 0.8, 'htc': 1, '_id': ObjectId('58e8d03958ae6d179c2b4413'), 'ftc': 1},
    {'rtc': 0, 'vf': 2, 'mtc': 1, 'doc': 'test', 'foc': 45, 'st': 0.8, 'htc': 12, '_id': ObjectId('58e8d03958ae6d180c2b4446'), 'ftc': 0}
]

基于条件的字典,如果“doc”键值文本相同,则应删除其中一个字典。我尝试了以下解决方案:

distinct_cur = [dict(y) for y in set(tuple(x.items()) for x in cur)]

但最终列表中仍然存在重复项。

以下是所需的输出,如第一个和第二个 distinct_cur 键值相同的文本(干得好):

[
    {'rtc': 0, 'vf': 0, 'mtc': 0, 'doc': 'good job', 'foc': 195, 'st': 0.0, 'htc': 2, '_id': ObjectId('58e86a550a0aeff4e14ca6bb'), 'ftc': 0}, 
    {'rtc': 0, 'vf': 2, 'mtc': 1, 'doc': 'test', 'foc': 45, 'st': 0.8, 'htc': 12, '_id': ObjectId('58e8d03958ae6d180c2b4446'), 'ftc': 0}
]

【问题讨论】:

标签: python


【解决方案1】:

您正在使用不同的元素创建 set,并期望它会根据只有您知道的标准删除重复项。

您必须遍历您的列表,并且仅当 doc 的值与之前的值不同时才添加到结果列表中: 比如这样:

done = set()
result = []
for d in distinct_cur:
    if d['doc'] not in done:
        done.add(d['doc'])  # note it down for further iterations
        result.append(d)

通过在辅助集中注册已知键,将仅保留具有相同 doc 键的字典的第一次出现。

另一种可能性是使用带有键作为字典的"doc" 键的字典,在列表中向后迭代,以便第一个项目覆盖列表中的最后一个:

result = {i['doc']:i for i in reversed(distinct_cur)}.values()

【讨论】:

    【解决方案2】:

    我看到 2 个类似的解决方案取决于您的域问题:您要保留键的 first 实例还是 last 实例?

    使用last(以便覆盖之前的匹配项)更简单:

    d = {r['doc']: r for r in distinct_cur}.values()
    

    【讨论】:

      【解决方案3】:

      在doc的primary_key上删除字典列表distinct_cur的重复数据

      [i for n, i in enumerate(distinct_cur) if i.get('doc') not in [y.get('doc') for y in distinct_cur[n + 1:]]]
      

      【讨论】:

        【解决方案4】:

        试试这个:

        distinct_cur  =[dict(t) for t in set([tuple(d.items()) for d in distinct_cur])]
        

        为我工作...

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2011-10-28
          • 1970-01-01
          • 2016-06-11
          • 2016-03-14
          • 2019-01-09
          • 2022-11-27
          • 2017-07-04
          • 2013-09-01
          相关资源
          最近更新 更多