1

I have a flask server that is sending a dictionary to the frontend. I'm trying to sort the contents of the dictionary in the UI.

Here is how the dictionary is structured.

{
 'Var1':
        {
         'weight':1,
         'other_stuff':'foo'
        },
 'Var2':
        {
         'weight':0.5,
         'other_stuff':'bar'
        },
 'Var3':
        {
         'weight':2,
         'other_stuff':'baz'
        },
...
}

The relevant snippet from the UI that isn't what I need to sort looks something like this. Note this works just fine, no errors, but it isn't sorting the data.

{% for key,var in d %}
    <tr>
    <td>{{ key }}</td>
    {% if var['weight']>0.01 or var['weight']<-0.01 %}
    <td>{{ var['weight'] }}</td>
    {% else %}
    <td>0.01</td>
    {% endif %}
  </tr>
{% endfor %}

What I want to do is to sort this dictionary when displaying it, obviously dictionaries have no ordering in python, by the weight. Desired output would be the data being displayed like this:

<tr>
    <td>Var3</td>
    <td>2</td>
</tr>
<tr>
    <td>Var1</td>
    <td>1</td>
</tr>
<tr>
    <td>Var2</td>
    <td>0.5</td>
</tr>

I've tried to use do_dictsort filter, but it gave me an error because of how the data was organized. How do I sort this in the UI?

Ryan
  • 259
  • 3
  • 10
  • 1
    why would you not sent an `orderdict` instead – modesitt Aug 20 '18 at 16:10
  • https://docs.python.org/3/library/collections.html#collections.OrderedDict should maintain ordering when iterated over in Jinja – bphi Aug 20 '18 at 16:12
  • You can convert your dict of dicts to a list of dicts (moving a key inside an inner dictionary) and use [this](https://stackoverflow.com/questions/1959386/how-do-you-sort-a-list-in-jinja2) solution. – taras Aug 20 '18 at 16:13
  • Well geez, if you guys want to make it that easy, an ordered dictionary should work, sure. I didn't even think of solving it on the backend side. – Ryan Aug 20 '18 at 16:27

1 Answers1

1

why don't you send the sorted dict to the front end..now you just have to loop.

here's how

   data = sorted(d.items(), key=lambda x: x[1]['weight'], reverse=True)

{% for key,var in d %}
   <table>
    <tr>
    <td>{{ key }}</td>
    <td>{{ var['weight'] }}</td>
  </tr>
</table>
{% endfor %}
iamklaus
  • 3,720
  • 2
  • 12
  • 21