【问题标题】:How to deduplicate the dictionaries that contain the same id in python如何对python中包含相同id的字典进行重复数据删除
【发布时间】:2021-10-11 09:53:34
【问题描述】:

我想删除包含相同“id”值的字典。

字典列表:

example = [{'term': 'potato', 'id': 10}, {'term': 'potatoes', 'id': 10}, {'term': 'apple', 'id': 7}]

期望的输出:

example = [{'term': 'potato', 'id': 10}, {'term': 'apple', 'id': 7}]

目前我只能删除所有重复项,而不是保留一个;或者只删除那些完全相同的字典,而我只是想删除那些具有相同 id 值的字典。

示例代码(尝试):

import ast 

new_list = []
seen_keys = set()
for term in example:
    d = ast.literal_eval(term) #had to convert a string-dict to a dict first because the dictionaries were transformed to a string in a Solr database
    if d['id'] not in seen_keys:
        new_list.append(d)
        seen_keys.add(d['id'])

【问题讨论】:

    标签: python python-3.x list dictionary


    【解决方案1】:

    不用ast.literal_eval:

    example = [{'term': 'potato', 'id': 10}, {'term': 'potatoes', 'id': 10}, {'term': 'apple', 'id': 7}]
    
    seen_keys = set()
    new_list = []
    for d in example:
        if d["id"] not in seen_keys:
            seen_keys.add(d["id"])
            new_list.append(d)
    
    print(new_list)
    

    输出

    [{'term': 'potato', 'id': 10}, {'term': 'apple', 'id': 7}]
    

    如果您对O(n) 单行感兴趣,请使用:

    new_list = list({ d["id"] : d for d in example[::-1]}.values())[::-1]
    print(new_list)
    

    输出 (来自单行)

    [{'term': 'potato', 'id': 10}, {'term': 'apple', 'id': 7}]
    

    【讨论】:

      【解决方案2】:

      我有点喜欢为这类问题创建一个通用的 uniqueBy 函数:

      
      example = [{'term': 'potato', 'id': 10}, {'term': 'potatoes', 'id': 10}, {'term': 'apple', 'id': 7}]
      
      def uniqueBy (f):
          return lambda a: { f(x): x for x in a }
      
      uniqueById = uniqueBy(lambda x: x['id'])
          
      print("{}".format(uniqueById(example).values()))
      

      【讨论】:

        【解决方案3】:

        或者使用enumerate 的单行列表理解:

        >>> [d for i, d in enumerate(example) if d['id'] not in [x['id'] for x in example[i + 1:]]]
        [{'term': 'potatoes', 'id': 10}, {'term': 'apple', 'id': 7}]
        >>> 
        

        【讨论】:

          【解决方案4】:

          你可以试试这个

          example = [
              {"term": "potato", "id": 10},
              {"term": "potatoes", "id": 10},
              {"term": "apple", "id": 7},
          ]
          
          ids = set()
          
          for item in example:
              ids.add(item["id"])
          
          results = []
          
          for item in example:
              if item["id"] in ids:
                  results.append(item)
                  ids.remove(item["id"])
          
          print(results)
          

          【讨论】:

            【解决方案5】:

            这很容易做到:

            test_list = [{'term': 'potato', 'id': 10}, {'term': 'potatoes', 'id': 10}, {'term': 'apple', 'id': 7}]
            
            
            res = []
            [res.append(x) for x in test_list if x['id'] not in [y['id'] for y in res]]
            print(res)
            

            【讨论】:

              【解决方案6】:

              对您的代码稍作修改后:

              example = [{'term': 'potato', 'id': 10}, {'term': 'potatoes', 'id': 10}, {'term': 'apple', 'id': 7}]
              new_list = []
              seen_keys = set()
              
              for i in example:
                  if i['id'] not in seen_keys:
                      new_list.append(i)
                      seen_keys.add(i['id'])
                      
              print(new_list)
              

              输出:

              [{'term': 'potato', 'id': 10}, {'term': 'apple', 'id': 7}]
              

              【讨论】:

                猜你喜欢
                • 2020-01-16
                • 1970-01-01
                • 2014-01-27
                • 1970-01-01
                • 1970-01-01
                • 2018-08-30
                • 2020-09-05
                • 2020-04-16
                • 1970-01-01
                相关资源
                最近更新 更多