python - Ordering dictionary values on Jinja2 template -
i using jinja2 template render information report. creating table showing max, total, avg_size , avg_rate types of events occuring on system.
my code creates new row after every 6 entries, , prints data looks correct on closer inspection it's not printing data in correct order because i'm using 'if' statements.
is there away can make key2=='max_count'
first print it's value, key2 == 'total'
, etc.
the order want:
max_count, total, avg_size, avg_rate
here part of code causing issue:
{% key2, value2 in max_min_data[key].iteritems() %} {% if count == 6 %} </tr> <tr> {% set count = 0 %} {% endif %} {% if key2 == 'max_count'%} <td style="text-align: center; width:3.1in;">{{ '{0:,}'.format(value2['max']) }}</td> {% endif %} {% if key2 == 'total'%} <td style="text-align: center; width:3.1in;">{{'{0:,}'.format(value2['max'])}}</td> {% endif %} {% if key2 == 'avg_size'%} <td style="text-align: center; width:3.1in;">{{'{0:,}'.format(value2['max'])}}</td> {% endif %} {% if key2 == 'avg_rate'%} <td style="text-align: center; width:3.1in;">{{'{0:,}'.format(value2['max'])}}</td> {% endif %} {% set count = count + 1 %} {% endfor %}
example of dictionary looping through:
{ 'event1': { 'avg_rate': {'max': 11004, 'min': 0}, 'avg_size': {'max': 219, 'min': 218}, 'total': {'max': 107743, 'min': 103354}, 'max_count': {'max': 103756, 'min': 103094} }, 'event2': { 'avg_rate': {'max': 558, 'min': 0}, 'avg_size': {'max': 321, 'min': 319}, 'total': {'max': 11029, 'min': 10046}, 'max_count': {'max': 17724, 'min': 17585} }, 'event3': { 'avg_rate': {'max': 1824, 'min': 0}, 'avg_size': {'max': 363, 'min': 360}, 'total': {'max': 48737, 'min': 46529}, 'max_count': {'max': 47094, 'min': 46711} } }
default dictionaries in python not ordered. can use ordereddict collections
module in standard library:
from collections import ordereddict d = { 'event1': ordereddict([ ('avg_rate', {'max': 11004, 'min': 0}), ('avg_size', {'max': 219, 'min': 218}), ('total', {'max': 107743, 'min': 103354}), ('max_count', {'max': 103756, 'min': 103094}) ]), 'event2': ordereddict([ ('avg_rate', {'max': 558, 'min': 0}), ('avg_size', {'max': 321, 'min': 319}), ('total', {'max': 11029, 'min': 10046}), ('max_count', {'max': 17724, 'min': 17585}) ]), 'event3': ordereddict([ ('avg_rate', {'max': 1824, 'min': 0}), ('avg_size', {'max': 363, 'min': 360}), ('total', {'max': 48737, 'min': 46529}), ('max_count', {'max': 47094, 'min': 46711}) ]) } event in d: print(event) key in d[event]: print('\t{}'.format(key))
output:
event2 avg_rate avg_size total max_count event3 avg_rate avg_size total max_count event1 avg_rate avg_size total max_count
Comments
Post a Comment