I built a data structure like this:
{ level: [ event1, event2... ] }
The level is one of the following: C(stands for critical), H(stands for high), M(stands for medium), L(stands for low).
I want to print all events in django template based on the level, C(critical) comes first, then H(high), M(medium), L(low). However, by default, which is what I have:
{% for level, events in dictionary.items %}
{% for event in events %}
do something with level, event
{% endfor %}
{% endfor %}
I got H(high) printed out first, then C(critical), etc. I want to ask: How can I loop a dictionary in particular order? Or should I convert it into other data structure? Thanks.
Edit:
I think Steve’s method works fine. It converts a dictionary into a list, each entry of the dictionary becomes a tuple:
[ (level1: [event1, event2 ...]), (level2: [event3, event4 ...]) ]
Dictionaries are not ordered, so you will need to convert them to a list of tuples first:
Sort them as follows:
Then pass in your sorted_dictionary variable, and loop it in the same way as before:
Further explanation of the important statement:
dictionary.items()gives you a list of tuples, representing your original dictionary. So instead of a dictionary like this:if gives you a list of tuples, for each key/value pair in the dictionary:
You can think of a tuple as an list that can’t be changed (it’s said to be ‘immutable’).
This list of tuples is then passed into the
sortedfunction. For each tuple in the list,sorted()calls the lambda expression we supplied to ask for a sorting key. Our lambda expression simply takes the first element in the tuple (i.e. the severity value), and accesses thelevel_valuesdictionary to find a sort value for it.You can loop through the resulting
sorted_dictionary(which is a list of tuples) either tuple by tuple:or Python will let you automatically split the tuble into separate variables: