I have a list of tuples:
[ (a,1), (a,2), (b,1), (b,3) ]
I want to get the sum of both the a
and b
values. The results should be in this format:
[ { 'key' : a, 'value' : 3 }, {'key' : b, 'value' : 4 } ]
How can I do this?
from itertools import groupby
[{'key': k, 'value': sum(v for _,v in g)} for k, g in groupby(sorted(lst), key = lambda x: x[0])]
# [{'key': 'a', 'value': 3}, {'key': 'b', 'value': 4}]
from collections import defaultdict
lst = [("a", 1), ("a", 2), ("b", 1), ("b", 3)]
out = defaultdict(list)
[out[v[0]].append(v[1]) for v in lst]
out = [{"key": k, "value": sum(v)} for k, v in out.iteritems()]
print out
You can use collections.Counter
to create a multiset from the initial list and then modify the result to match your case:
from collections import Counter
lst = [('a', 1), ('a', 2), ('b', 1), ('b', 3)]
part = sum((Counter({i[0]: i[1]}) for i in lst), Counter())
# Counter({'b': 4, 'a': 3})
final = [{'key': k, 'value': v} for k, v in part.items()]
# [{'key': 'b', 'value': 4}, {'key': 'a', 'value': 3}]
Very similar to answers given already. Little bit longer, but easier to read, IMHO.
from collections import defaultdict
lst = [('a', 1), ('a', 2), ('b', 1), ('b', 3)]
dd = defaultdict(int)
for name, value in lst:
dd[name] += value
final = [{'key': k, 'value': v} for k, v in dd.items()]
(last line copied from Moses Koledoye's answer)
from collections import Counter
a = [('a', 1), ('a', 2), ('b', 1), ('b', 3)]
c = Counter()
for tup in a:
c = c + Counter(dict([tup]))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.