Matthias Scholz
Matthias Scholz

Reputation: 1035

Output sorted python dict within django template

I got a python dict, that looks like the following (Important informations were replaced with "xxx" due to privacy reasons). I would like to display this dict within a django template but it should be ordered, so it should start with "A", then continue with "B" instead of "H"

This is my dict (shortened):

{   'A': [   {'birthday_date': None,
             'first_name': 'Alberto',
             'last_name': 'xxx',
             'name': 'Alberto xxx',
             'uid': xxx},
         {   'birthday_date': None,
             'first_name': 'Antony',
             'last_name': 'xxx',
             'name': 'Antony xxx',
             'uid': xxx}],
'H': [   {   'birthday_date': '08/28',
             'first_name': 'Hitoshi',
             'last_name': 'xxx',
             'name': 'Hitoshi xxx',
             'uid': xxx}],
'C': [   {   'birthday_date': '05/07/1985',
             'first_name': 'Chr',
             'last_name': 'xxx',
             'name': 'Chr xxx',
             'uid': xxx}],
'E': [   {   'birthday_date': None,
             'first_name': 'Edimond',
             'last_name': 'xxx',
             'name': 'Edimond xxx',
             'uid': xxx},
         {   'birthday_date': '08/30',
             'first_name': 'Erika',
             'last_name': 'xxx',
             'name': 'Erika xxx',
             'uid': xxx}],
'B': [   {   'birthday_date': '08/16/1987',
             'first_name': 'Bhaktin',
             'last_name': 'xxx',
             'name': 'Bhaktin xxx',
             'uid': xxx}],
'I': [   {   'birthday_date': '08/25/1987',
             'first_name': 'Ivette',
             'last_name': 'xxx',
             'name': 'Ivette xxx',
             'uid': xxx}]}

This is my django template:

{% for letter, friend in bdays_all.items %}
    <h2>{{ letter }}</h2>
    {% for user in friend %}
         ...
    {% endfor %}
{% endfor %}

This works well, but its not ordered. But thats what I need. I tried everything with python's sorted() function but without any successs. I only want to order the letters. Seems trivial but I guess it isn't.

Any ideas?

Thanks alot in advance!

Upvotes: 3

Views: 3855

Answers (2)

doru
doru

Reputation: 9110

You also could create a new dictionary with sorted keys in your view:

dictio = {'a': 'orange', 'c':'apple', 'b': 'bannana'}
di = {}
for key in sorted(dictio.iterkeys()):
    di[key] = dictio[key]

whit the result:

di = {'a': 'orange', 'b': 'bannana', 'c': 'apple'}

Upvotes: 0

Daniel Roseman
Daniel Roseman

Reputation: 599490

Dictionaries are unsorted.

You will need to convert your dict to a nested list in the view: the easiest way would be just to call sorted(bdays_all.items()).

Upvotes: 10

Related Questions