Home > Net >  How to sort a list of dictionaries alphabetically in Jinja2
How to sort a list of dictionaries alphabetically in Jinja2

Time:12-14

My sample list of dictionaries is shown below:

mydata = [{'data': [27, 3, 30, None, None], 'name': 'S1'}, {'data': [57.33, 6.37, 63.7, None, None], 'name': 'A2'}, {'data': [2349.62, 261.09, 2610.71, 0, 0], 'name': 'Total'}]

I want to sort the whole list of dictionaries alphabetically on the basis of key name but have to exclude the last element of the list, which name is Total.
The dictionary where the name is Total should be the last element of the list.

How should I proceed?

I tried something like below:

<div >
    <table >
        <tr>
            <th>Name</th>
            {% for data in mydata |sort(attribute='0.name')  %}
            <th>{{ data["name"] }}</th>
            {% endfor %}
        </tr>
    </table>
</div>

It's not sorting the data as expected.
Also how to keep the dictionary named Total at the end?

CodePudding user response:

You could reject the element of name Total, thanks to the filter rejectattr, then sort the resulting list.
Then, select the element of name Total only, with the filter selectattr and add it back to the end of the list

Given:

{%- set mydata = [{'data': [2349.62, 261.09, 2610.71, 0, 0], 'name': 'Total'},
    {'data': [27, 3, 30, None, None], 'name': 'S1'}, 
    {'data': [57.33, 6.37, 63.7, None, None], 'name': 'A2'},]
-%}

{% for data in 
    mydata | rejectattr('name', '==', 'Total') | sort(attribute='name') | list 
      mydata | selectattr('name', '==', 'Total') | list 
%}
  {{ data["name"] }}
{% endfor %}

This yields:


  A2 
 
  S1 
 
  Total
  • Related