octopusgrabbus
octopusgrabbus

Reputation: 10685

Best way to reduce dictionary of lists

I am asking this question to get a starting point of the Pythonic way to reduce some of the list contents in the following dictionary using list comprehensions:

{'cycle1': [1, 2407, 2393, 14],
 'cycle2': [2, 1657, 1652, 5], 
 'cycle3': [3, 2698, 2673, 25], 
 'cycle4': [4, 2116, 2102, 14], 
 'cycle5': [5, 2065, 2048, 17], 
 'cycle6': [6, 1633, 1615, 18]}

Each list's columns, though not marked, have these headers:

section_num,account_total,billable_count,nonbillable_count

I want to sum each of the last three columns, account_total, billable_count, non-billable_count in a list comprehension.

I'm just not sure how to sum going through each list member in a comprehension. I need to ask for the values of each key, each value being a list. I'm just a little unsure about how to do that.

Upvotes: 2

Views: 98

Answers (2)

Fredrik Pihl
Fredrik Pihl

Reputation: 45652

a bit unclear about the output-format requested, but the line below sums the second column:

In [13]: c = {'cycle1': [1, 2407, 2393, 14],
 'cycle2': [2, 1657, 1652, 5], 
 'cycle3': [3, 2698, 2673, 25], 
 'cycle4': [4, 2116, 2102, 14], 
 'cycle5': [5, 2065, 2048, 17], 
 'cycle6': [6, 1633, 1615, 18]}

In [14]: sum([v[1] for k, v in c.iteritems()])
Out[14]: 12576

Using python3.3

>>> sum([v[1] for v in c.values()])
12576

Upvotes: 2

squiguy
squiguy

Reputation: 33370

How about using zip? This does an individual sum of each column, although I'm not sure that is what you want.

[sum(x) for x in zip(*my_dict.values())[1:]]

This outputs:

[12576, 12483, 93]

Upvotes: 3

Related Questions