【问题标题】:Pop a dictionary when one of the values are identical (python)当其中一个值相同时弹出字典(python)
【发布时间】:2021-07-02 09:11:19
【问题描述】:

我有一个字典列表,其中每个字典的值都不同,除了 'name' 的值:

   list_dicts = [{'id': 12345, 'name': 'Bobby Bobs', 'pets': ['cat']},
                 {'id': 678910, 'name': 'Bobby Bobs', 'pets': ['zebra']},
                 {'id': 111213, 'name': 'Lisa Bobs', 'pets': ['horse']},
                 {'id': 141516, 'name': 'Lisa Bobs', 'pets': ['rabbit']}] 

我想在名称相同的情况下删除第二个字典,同时将额外的宠物值添加到第一个字典中。

想要的输出:

  output_list_dicts = [{'id': 12345, 'name': 'Bobby Bobs', 'pets': ['cat', 'zebra']},
                       {'id': 111213, 'name': 'Lisa Bobs', 'pets': ['horse', 'rabbit']}]

我主要是在努力识别具有相同值的项目。我假设在找到这些之后,可以将这些项目“附加”到“宠物”嵌套列表中,并使用“流行”消除其他字典。

【问题讨论】:

    标签: python list dictionary


    【解决方案1】:

    由于name 是独一无二的,因此您最好将其作为您的字典键,这样您就可以轻松测试您之前是否访问过它。然后使用dict.values() 可以得到你想要的列表输出。

    output = {}
    for list_dict in list_dicts:
        if list_dict['name'] in output:
            output[list_dict['name']]['pets'].extend(list_dict['pets'])
        else:
            output[list_dict['name']] = list_dict
    
    output_list_dicts = list(output.values())
    
    print(output_list_dicts)
    #[{'id': 12345, 'name': 'Bobby Bobs', 'pets': ['cat', 'zebra']},
    # {'id': 111213, 'name': 'Lisa Bobs', 'pets': ['horse', 'rabbit']}]
    

    【讨论】:

      【解决方案2】:

      您可以使用dict.setdefault 执行任务:

      list_dicts = [
          {"id": 12345, "name": "Bobby Bobs", "pets": ["cat"]},
          {"id": 678910, "name": "Bobby Bobs", "pets": ["zebra"]},
          {"id": 111213, "name": "Lisa Bobs", "pets": ["horse"]},
          {"id": 141516, "name": "Lisa Bobs", "pets": ["rabbit"]},
      ]
      
      output = {}
      for d in list_dicts:
          output.setdefault(
              d["name"], {"id": d["id"], "name": d["name"], "pets": []}
          )["pets"].extend(d["pets"])
      
      output = list(output.values())
      print(output)
      

      打印:

      [{'id': 12345, 'name': 'Bobby Bobs', 'pets': ['cat', 'zebra']}, {'id': 111213, 'name': 'Lisa Bobs', 'pets': ['horse', 'rabbit']}]
      

      【讨论】:

        【解决方案3】:

        您可以为此使用itertools.groupby

        import itertools
        
        list_dicts = sorted(list_dicts, key=lambda x: x["name"])
        output_list_dicts = []
        for key, group in itertools.groupby(list_dicts, key=lambda x: x["name"]):
            group = list(group)
            for g in group[1:]:
                group[0]["pets"].extend(g["pets"])
            output_list_dicts.append(group[0])
        
        print(output_list_dicts)
        

        输出:

        [{'id': 12345, 'name': 'Bobby Bobs', 'pets': ['cat', 'zebra']}, {'id': 111213, 'name': 'Lisa Bobs', 'pets': ['horse', 'rabbit']}]
        

        【讨论】:

          猜你喜欢
          • 2021-10-22
          • 1970-01-01
          • 1970-01-01
          • 2022-08-18
          • 1970-01-01
          • 2019-09-18
          • 1970-01-01
          相关资源
          最近更新 更多