Code


Version 5 (modified by kiwi, 5 years ago) (diff)

Example how to correctly create new SortedDict.

SortedDict

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

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.

d2 = SortedDict()
d2['b'] = 1
d2['a'] = 2
d2['c'] = 3