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

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



转载于:https://www.cnblogs.com/abeen/archive/2011/10/10/2205640.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值