How to add elements from a dictonary of lists in python -


given dictionary of lists

vd = {'a': [1,0,1], 'b':[-1,0,1], 'c':[0,1,1]} 

i want add lists element wise. want add first element list first element of list b vice versa complexity cannot rely on labels being a, b, c. can anything. second length of dictionary variable. here 3. 30.

the result need list [0, 1, 3]

in short:

>>> map(sum, zip(*vd.values())) [0, 1, 3] 

explanation

given dictionary:

>>> vd = {'a': [1,0,1], 'b': [-1,0,1], 'c': [0,1,1]} 

we can get values:

>>> values = vd.values() >>> values [[1, 0, 1], [-1, 0, 1], [0, 1, 1]] 

then zip them up:

>>> zipped = zip(*values) >>> zipped [(1, -1, 0), (0, 0, 1), (1, 1, 1)] 

note zip zips each argument; doesn't take list of things zip up. therefore, need * unpack list arguments.

if had 1 list, sum them:

>>> sum([1, 2, 3]) 6 

however, have multiple, can map on it:

>>> map(sum, zipped) [0, 1, 3] 

all together:

>>> map(sum, zip(*vd.values())) [0, 1, 3] 

extending average rather sum

this approach extensible; example, quite make average elements rather sum them. that, we'd first make average function:

def average(numbers):     # have float(...) doesn't integer division.     # in python 3, not necessary.     return sum(numbers) / float(len(numbers)) 

then replace sum average:

>>> map(average, zip(*vd.values())) [0.0, 0.3333, 1.0] 

Comments

Popular posts from this blog

html5 - What is breaking my page when printing? -

html - Unable to style the color of bullets in a list -

c# - must be a non-abstract type with a public parameterless constructor in redis -