Version 8 (modified by Juarez Bochi, 12 years ago) ( diff )

--

SortedDict

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

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