【问题标题】:How to combine dictionaries within an array based on the same key-value pairs?如何根据相同的键值对在数组中组合字典?
【发布时间】:2015-03-31 10:32:45
【问题描述】:

例如,在下面的列表中,我想合并所有共享相同 'id' 和 'name' 的字典。

输入:

l = [{'id':'1','name':'a','key1':'1'},
     {'id':'1','name':'a','key2':'3'},
     {'id':'1','name':'a','key3':'4'},
     {'id':'2','name':'a','key5':'1'},
     {'id':'2','name':'a','key7':'c'},
     {'id':'1','name':'b','key5':'1'}]

期望的结果:

l = [{'id':'1','name':'a','key1':'1','key2':'3','key3':'4'},
     {'id':'2','name':'a','key5':'1','key7':'c'},
     {'id':'1','name':'b','key5':'1'}]

如果可能,我希望该函数还采用不同数量的参数,字典必须共享哪些键才能组合它们。例如,如果我只想基于“id”而不是“key”和“name”进行组合,结果会有所不同。

【问题讨论】:

标签: python arrays dictionary


【解决方案1】:

itertools.groupby 为您进行分组。剩下要做的就是将字典的可迭代列表(按 id 分组)合并到字典列表中:

>>> import itertools    
>>> l = [ dict(reduce(lambda a, b: a + b.items(), lst, [])) for lst in \
          [ list(grouper) for key, grouper in \
            itertools.groupby(l, lambda x: (x["id"], x["name"])) ] \
        ]
>>> l
[{'id': '1', 'key1': '1', 'key2': '3', 'key3': '4', 'name': 'a'},
 {'id': '2', 'key5': '1', 'key7': 'c', 'name': 'a'},
 {'id': '1', 'key5': '1', 'name': 'b'}]

这显然不是最易读的版本;您可能应该使用合并字典而不是嵌套列表推导的辅助函数。

【讨论】:

    【解决方案2】:

    传统方式:D

    result = []
    
    for item in l :
        check = False
        # check item, is it exist in result yet (r_item)
        for r_item in result :
            if item['id'] == r_item['id'] and item['name'] == r_item['name'] :
                # if found, add all key to r_item ( previous record)
                check = True
                r_item.update( item )
        if check == False :
            # if not found, add item to result (new record)
            result.append( item )
    

    【讨论】:

      猜你喜欢
      • 2018-01-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多