【问题标题】:Merge lists within dictionaries with the same keys使用相同的键合并字典中的列表
【发布时间】:2022-12-03 06:05:59
【问题描述】:

我在这样的列表中有以下三个词典:

dict1 = {'key1':'x', 'key2':['one', 'two', 'three']}

dict2 = {'key1':'x', 'key2':['four', 'five', 'six']}

dict3 = {'key1':'y', 'key2':['one', 'two', 'three']}

list = [dict1, dict2, dict3]

我想将 key1 具有相同值的字典合并到一个具有 key2 合并值(在本例中为列表)的字典中,如下所示:

new_dict = {'key1':'x', 'key2':['one', 'two', 'three', 'four', 'five', 'six']}

list = [new_dict, dict3]

我提出了一个充满硬代码和循环的非常野蛮的解决方案。我想使用一些高阶函数,但我是新手。

【问题讨论】:

    标签: python list dictionary


    【解决方案1】:

    构建一个使用 key1 作为聚合 key2 列表的键的中间字典,然后从中构建最终的字典列表:

    >>> my_dicts = [
    ...     {'key1':'x', 'key2':['one', 'two', 'three']},
    ...     {'key1':'x', 'key2':['four', 'five', 'six']},
    ...     {'key1':'y', 'key2':['one', 'two', 'three']},
    ... ]
    >>> agg_dict = {}
    >>> for d in my_dicts:
    ...     agg_dict.setdefault(d['key1'], []).extend(d['key2'])
    ...
    >>> [{'key1': key1, 'key2': key2} for key1, key2 in agg_dict.items()]
    [{'key1': 'x', 'key2': ['one', 'two', 'three', 'four', 'five', 'six']}, {'key1': 'y', 'key2': ['one', 'two', 'three']}]
    

    【讨论】:

      【解决方案2】:

      itertools.groupbyitertools.chain 的帮助下,您的目标可以在一行中实现:

      from itertools import groupby
      from itertools import chain
      
      dict1 = {'key1':'x', 'key2':['one', 'two', 'three']}
      dict2 = {'key1':'x', 'key2':['four', 'five', 'six']}
      dict3 = {'key1':'y', 'key2':['one', 'two', 'three']}
      list_of_dicts = [dict1, dict2, dict3]
      
      result = [{'key1': k, 'key2': list(chain(*[x['key2'] for x in v]))} for k, v in groupby(list_of_dicts, lambda x: x['key1'])]
      
      print(result)
      [{'key1': 'x', 'key2': ['one', 'two', 'three', 'four', 'five', 'six']}, {'key1': 'y', 'key2': ['one', 'two', 'three']}]
      

      【讨论】:

        猜你喜欢
        • 2015-08-25
        • 2019-11-19
        • 2020-10-14
        • 2019-06-20
        • 2021-07-29
        • 1970-01-01
        • 2021-11-26
        • 1970-01-01
        • 2021-08-22
        相关资源
        最近更新 更多