Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 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?

like image 707
Gaurav Jain Avatar asked Nov 06 '25 16:11

Gaurav Jain


1 Answers

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.

like image 53
Martijn Pieters Avatar answered Nov 09 '25 10:11

Martijn Pieters



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!