Python sum dict values based on keys

后端 未结 3 1593
遥遥无期
遥遥无期 2021-01-15 14:11

How to sum values from dict where values are string. I mean how to sum values where multiply key is same in dictionary.

dict

values = [
    {
                


        
3条回答
  •  爱一瞬间的悲伤
    2021-01-15 14:20

    Specific solution, with no attempt at cleverness:

    def regroup(values):
        groups = dict()
        for d in values:
            key = (d["prod_name"], d["prod_hola"])
            if key in groups:
                group = groups[key]
                group["rashod"] += d["rashod"]
                group["prihod"] += d["prihod"]
            else:
                groups[key] = d.copy()
        return list(groups.values())
    

    And a slightly more generic solution:

    def generic_regroup(values, keys):
        groups = dict()
        valkeys = [k for k in values[0] if k not in key]
        for d in values:
            key = tuple(d[k] for k in keys)
            if key in groups:
                group = groups[key]
                for k in valkeys:
                    group[k] += d[k]
            else:
                groups[key] = d.copy()
        return list(groups.values())
    
    results = generic_regroup(values, ("prod_name", "prod_hola"))
    

    Now someone will certainly chime in with a much more clever solution involving itertools...

提交回复
热议问题