python - Merging tuples with same head in list -
this question has answer here:
- python list grouping , sum 5 answers
i have list composed tuples.
each tuple in following tuple format: (string, integer).
i want merge tuples have same head (string) follows:
[("foo", 2), ("bar", 4), ("foo", 2), ("bar", 4), ("foo", 2)]
should become:
[("foo", 6), ("bar",8)].
what python algorithm this?
how collecting sums in defaultdict
?
from collections import defaultdict d = defaultdict(int) (key, value) in items: d[key] += value
and turn them list of tuples:
list(d.items())
the defaultdict
in example uses int
function fill in unknown values 0
. first time particular d[key]
added to, assumes initial value of 0
, gets summed there.
Comments
Post a Comment