python - Merging tuples with same head in list -


this question has answer here:

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

Popular posts from this blog

jquery - uncaught exception: DataTables Editor - remote hosting of code not allowed -

java - SSE Emitter : Manage timeouts and complete() -

java - How to resolve error - package com.squareup.okhttp3 doesn't exist? -