Re: Sorting a dict by value for template rendering

2008-05-16 Thread Peter Rowell

Variations on this come up all the time. Note that arrays can be
sorted.
So, create an array of tuples containing the key and the value.
Then you can sort the array anyway you please.

In the view:
# create the array of tuples
ordered_dict = [(key, val) for key,val in my_original_dict.items()]

 # sort by key
ordered_dict.sort(lambda a,b: cmp(a[0], b[0]))
or
 # sort by value
ordered_dict.sort(lambda a,b: cmp(a[1], b[1]))

# if values are objects, you can do
ordered_dict.sort(lambda a,b: cmp(a[1].some_attr, b[1].some_attr))

In the template:

{% for item in ordered_dict %}
  Key: {{item.0}}  Value: {{item.1}}
{% for %}

HTH,
Peter
--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~--~~~~--~~--~--~---



Sorting a dict by value for template rendering

2008-05-16 Thread bfrederi

I have a dict that looks similar to this:
{'com': 'communication', 'tel': 'telephone', 'cel': 'cellphone',
'fax': 'fax machine',}

And I want to sort it by value, and render it in a template. I was
able to do it, but in a very hacked way. Can anyone show me a better
way to do it than my solution.

Here is the template tag (the dict I want to sort is
vocab_dict[vocabulary] on line 13):
http://dpaste.com/hold/50603/
Here is the template (the dict has been converted into a sorted list
of dicts and iterated through on lines 6-11):
http://dpaste.com/hold/50604/
--~--~-~--~~~---~--~~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~--~~~~--~~--~--~---