【问题标题】:Merge lists of dictionaries based on matching values in one key根据一键匹配值合并字典列表
【发布时间】:2022-01-05 16:35:51
【问题描述】:

我有一本字典

dicte = [{'value':3, 'content':'some_string'}, {'value':4, 'content':'some_string1'}, {'value':4, 'content':'some_string2'}, {'value':4, 'content':'some_string3'}, {'value':4, 'content':'some_string4'}, {'value':5, 'content':'some_string5'}]

我希望能够对该字典进行操作,以便对键 "value" 获得相同值的所有 content 进行重新分组,并根据该字典生成另一个字典

这里的结果应该是

new_dicte = [{'value':3, 'content':['some_string']}, {'value':4, 'content':['some_string1', 'some_string2', 'some_string3', 'some_string4']}, {'value':5, 'content':['some_string5']}]

最好的pythonic方法是什么?

【问题讨论】:

    标签: python python-3.x dictionary


    【解决方案1】:

    “Pythonic”值得商榷,但您可以构建一个中间字典来按值分组:

    grouped_by_value = {}
    
    for item in dicte:
        if item["value"] not in grouped_by_value:
            grouped_by_value[item["value"]] = []
    
        grouped_by_value[item["value"]].append(item["content"])
    
    new_dicte = [{"value": key, "content": val} for key, val in grouped_by_value.items()]
    

    假设您使用 Python字典按插入顺序排序的版本。

    如果要保证new_dicte 的特定排序,可以对grouped_by_value.items() 的项目进行排序,例如通过增加“value”键。

    【讨论】:

      【解决方案2】:

      这是使用dict.setdefault 方法收集value-content 对并稍后解包的一种方法:

      out = {}
      for d in dicte:
          out.setdefault(d['value'],[]).append(d['content'])
      new_dicte = list(map(lambda x: dict(zip(('value','content'), x)), out.items()))
      

      这是另一种不使用中间字典的方法:

      out = {}
      for d in dicte:
          if d['value'] not in out:
              out[d['value']] = {'value':d['value'], 'content':[d['content']]}
          else:
              out[d['value']]['content'].append(d['content'])
      new_dicte = list(out.values())
      

      输出:

      [{'value': 3, 'content': ['some_string']},
       {'value': 4,
        'content': ['some_string1', 'some_string2', 'some_string3', 'some_string4']},
       {'value': 5, 'content': ['some_string5']}]
      

      【讨论】:

      • @MohamedThabetBenAicha 我包括了一种更有效的方法,它不使用中间步骤。看看那个。
      【解决方案3】:

      Best Pythonic 值得商榷,但我个人会选择这样的东西,

      import itertools
      from collections import defaultdict
      
      resp = defaultdict(list)
      
      for key,group in itertools.groupby(d, key=lambda x: x["value"]):
          for thing in group:
              resp[key].append(thing.get("content"))
      
      print(resp)
      

      输出(可以调整到我们想要的方式...)

      {3: ['some_string'],
       4: ['some_string1', 'some_string2', 'some_string3', 'some_string4'],
       5: ['some_string5']}
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-09-17
        • 2021-01-10
        • 2016-02-22
        • 2021-06-24
        • 2021-07-26
        • 1970-01-01
        • 2022-11-28
        • 1970-01-01
        相关资源
        最近更新 更多