根据名字来理解sorteddict:排序过的字典。它支持按索引来操作字典。
A dictionary that keeps its keys in the order in which they're inserted.
它提供了两个有用的方法
insert(index, key, value) value_for_index(index)
注意事项:
d = SortedDict({ 'b': 1, 'a': 2, 'c': 3 })
上述方法是无效的,sorteddict不知道插入顺序。
下面的方法是有效的:
from django.utils.datastructures import SortedDict d2 = SortedDict() d2['b'] = 1 d2['a'] = 2 d2['c'] = 3
最后一个demo:
from django.utils.datastructures import SortedDict d2 = SortedDict() d2['b'] = 1 d2['a'] = 2 d2['c'] = 3 print d2 d2.insert(2,'f',4) print d2 print d2.value_for_index(0)
输出:
{'b': 1, 'a': 2, 'c': 3} {'b': 1, 'a': 2, 'f': 4, 'c': 3} 1