django的一个小功能——SortedDict


根据名字来理解sorteddict:排序过的字典。它支持按索引来操作字典。

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

它提供了两个有用的方法

[python]
insert(index, key, value) 
value_for_index(index) 

insert(index, key, value)
value_for_index(index)注意事项:

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

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

上述方法是无效的,sorteddict不知道插入顺序。

下面的方法是有效的:

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

from django.utils.datastructures import SortedDict
d2 = SortedDict()
d2['b'] = 1
d2['a'] = 2
d2['c'] = 3最后一个demo:


[python]
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) 

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)
输出:

[python]
{'b': 1, 'a': 2, 'c': 3} 
{'b': 1, 'a': 2, 'f': 4, 'c': 3} 

{'b': 1, 'a': 2, 'c': 3}
{'b': 1, 'a': 2, 'f': 4, 'c': 3}
1
 

 


 

相关内容

    暂无相关文章

评论关闭