Version 12 (modified by mdhowle, 10 years ago) ( diff )

Noted the deprecration of SortedDict

SortedDict

SortedDict is deprecated as of Django 1.7 and will be removed in Django 1.9. Use collections.OrderedDict instead. Available in Python 2.7 and 3.1+.

One of Django's custom data structure classes
source: http://code.djangoproject.com/browser/django/trunk/django/utils/datastructures.py#L124

A dictionary that keeps its keys in the order in which they're inserted.

Supports the following extra methods:

insert(index, key, value)
Inserts the key, value pair before the item with the given index."

value_for_index(index)
Returns the value of the item at the given zero-based index.

Creating new SortedDict

If you create new SortedDict using basic Python dict, SortedDict will not preserve key order. The reason is that SortedDict will receive (basic Python) unordered dictionary and therefore doesn't know about key order.

This does NOT work.

d = SortedDict({
	'b': 1,
	'a': 2,
	'c': 3
})

This works. SortedDict got keys in right order.

from django.utils.datastructures import SortedDict
d2 = SortedDict()
d2['b'] = 1
d2['a'] = 2
d2['c'] = 3

This also works.

d = SortedDict([
	('b', 1),
	('a', 2),
	('c', 3),
])
Note: See TracWiki for help on using the wiki.
Back to Top