How to merge dictionaries in a list based on a value in the dictionary in Python?
本问题已经有最佳答案,请猛点这里访问。
我有如下所示的字典列表:
1 2 3 4 5 | result = [ {'so': 'SO1', 'amt':250}, {'so': 'SO2', 'amt':200}, {'so': 'SO1', 'amt':100} ] |
我需要合并它,以便结果是:
1 2 3 4 | result = [ {'so': 'SO1', 'amt':350}, {'so': 'SO2', 'amt':200} ] |
即合并同一个
1 2 3 4 5 6 | from collections import Counter counters = [Counter({k['so']: k['amt']}) for k in result] r = sum(counters, Counter()) # Counter({'SO1': 350, 'SO2': 200}) result = [{'so': k, 'amt': r.get(k)} for k in r] # [{'so': 'SO1', 'amt': 350}, {'so': 'SO2', 'amt': 200}] |
我的解决方案:
1 2 3 | d = dict() for so, amt in map(lambda x: (x["so"],x["amt"]), result): d[so] = d.get(so, 0) + amt |
你想
解释:
1 2 3 4 5 | result = [ ('SO1', 250), ('SO2', 200), ('SO1', 100) ] |
试试这个。
1 2 3 4 5 6 7 8 | import collections data = collections.OrderedDict() for d in dictlist: so = d['so'] data.setdefault(so, 0) data[so] += d['amt'] result = [{'so':k, 'amt': v} for k, v in data.items()] |
希望这帮助