How to sum values from dict where values are string. I mean how to sum values where multiply key is same in dictionary.
values = [
{
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, [])