您的位置:首页 > 编程语言 > Python开发

[Dynamic Language] Python OrderedDict 保证按插入的顺序迭代输出

2011-10-10 15:25 453 查看
Python 2.7 中的OrderedDict 可以在迭代字典Items的时候保证按每项插入的顺序输出。
当删除某项再用同样的key写入时,此项排在迭代的最后,同样是插入顺序排列的。
可以用popitem的last=True/False来控制pop进返回最近插入的还是最早插入的,实际上就是维护了一个双向链表。

abeen@localhost:~$ python2.7
Python 2.7.2 (default, Oct  9 2011, 20:20:38)
[GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from collections import OrderedDict
>>> d = OrderedDict([('one',1), ('tow', 2), ('three', 3)])
>>> d.items()
[('one', 1), ('tow', 2), ('three', 3)]
>>> d['tow'] = 4
>>> d.items()
[('one', 1), ('tow', 4), ('three', 3)]
>>> d['tow']
4
>>> d.items()
[('one', 1), ('two', 4), ('three', 3)]
>>> del d['two']
>>> d.items()
[('one', 1), ('three', 3)]
>>> d['two'] = 4
>>> d.items()
[('one', 1), ('three', 3), ('two', 4)]
>>>


控制pop返回

>>> d = OrderedDict([(x,0) for x in range(10)])
>>> d.items()
[(0, 0), (1, 0), (2, 0), (3, 0), (4, 0), (5, 0), (6, 0), (7, 0), (8, 0), (9, 0)]
>>> d.popitem()
(9, 0)
>>> d.popitem()
(8, 0)
>>> d.items()
[(0, 0), (1, 0), (2, 0), (3, 0), (4, 0), (5, 0), (6, 0), (7, 0)]
>>> d.popitem(last=True)
(7, 0)
>>> d.popitem(last=True)
(6, 0)
>>> d.items()
[(0, 0), (1, 0), (2, 0), (3, 0), (4, 0), (5, 0)]
>>> d.popitem(last=False)
(0, 0)
>>> d.popitem(last=False)
(1, 0)
>>> d.items()
[(2, 0), (3, 0), (4, 0), (5, 0)]
>>>


字典项的迭代情况

In [1]: d = dict([('one',1), ('two', 2), ('three', 3)])

In [2]: d
Out[2]: {'one': 1, 'three': 3, 'two': 2}

In [3]: d.items()
Out[3]: [('three', 3), ('two', 2), ('one', 1)]

In [4]: d['two'] =4

In [5]: d
Out[5]: {'one': 1, 'three': 3, 'two': 4}

In [6]: d.items()
Out[6]: [('three', 3), ('two', 4), ('one', 1)]

In [7]: del d['two']

In [8]: d.items()
Out[8]: [('three', 3), ('one', 1)]

In [9]: d['two'] = 4

In [10]: d.items()
Out[10]: [('three', 3), ('two', 4), ('one', 1)]
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐