Python sum dict values based on keys

后端 未结 3 1614
遥遥无期
遥遥无期 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:28

    Here's a solution that uses a temporary dict with keys based on the input dict's key value pairs where the values are of type str:

    def get_key(d):
        return {k: v for k, v in d.items() if isinstance(v, str)}
    
    def sum_dicts(x, y):
        summed = {k: x.get(k, 0) + y[k] for k, v in y.items() if not isinstance(v, str)}
        summed.update(get_key(y))
        return summed
    
    result = {}
    for value in values:
        key = json.dumps(get_key(value))
        result[key] = sum_dicts(result.get(key, {}), value)
    
    print result.values()
    

    Or if you want to use reduce():

    def dict_sum_reducer(items, new):
        new_items = map(lambda x: sum_dicts(x, new) if get_key(x) == get_key(new) else x, items)
        if new_items == items:
            new_items.append(new)
        return new_items
    
    print reduce(dict_sum_reducer, values, [])
    

提交回复
热议问题