3

I have a list of dictionaries that I want to group by a certain attribute and then sum by another. For a variable 'foo' this would be something like:

foo | groupby('a') | sum(attribute='b')

This clearly won't work because after the groupby, I have a list of tuples. Is there any way to unpack the tuple and then repack it, so that i can maintain the work done by groupby, but work on the second tuple value?

dreftymac
  • 31,404
  • 26
  • 119
  • 182
Gaurav Jain
  • 33
  • 1
  • 4

1 Answers1

2

You can use the map() filter to apply a sum to each group, provided you extract the group list first:

foo | groupby('a') | map(attribute='list') | map('sum', attribute='b')

That's because map() takes the first argument as another filter, and the remainder of the arguments are passed to that filter, applying that filter to each element of groupby().

This does mean you end up with a list of sums, not with groups.

You cannot apply the summing to the groups and leave the .grouper attribute in place. For that the only solution is to use an actual loop:

{% for group in foo | groupby('a') %}
    {{ group.grouper }}: {{ group.list | sum(attribute='b') }}
{% endfor %}

would output each distinct value of a followed by a colon and the sum of attribute b for that group.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • Thanks, that's really helpful. Though unfortunate that I loose the `grouper`. It would've been nice if I could've extracted the `a` attribute with the `sum` operation to maintain the grouping. – Gaurav Jain Jan 18 '15 at 02:51