django的一个小功能——SortedDict

根据名字来理解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


 



 

posted @ 2013-05-28 11:06  jianhong  阅读(407)  评论(0编辑  收藏  举报