Gaurav Jain Gaurav Jain - 11 months ago 66
Python Question

Applying a jinja filter after using groupby filter

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
, 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
, but work on the second tuple value?

Answer Source

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.