[Dynamic Language] Python OrderedDict 保证按插入的顺序迭代输出
2011-10-10 15:25
453 查看
Python 2.7 中的OrderedDict 可以在迭代字典Items的时候保证按每项插入的顺序输出。
当删除某项再用同样的key写入时,此项排在迭代的最后,同样是插入顺序排列的。
可以用popitem的last=True/False来控制pop进返回最近插入的还是最早插入的,实际上就是维护了一个双向链表。
控制pop返回
字典项的迭代情况
当删除某项再用同样的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)]
相关文章推荐
- LinkedHashMap保证MAP按照插入的顺序输出
- 编写一个在1,2,…,9(顺序不能变)数字之间插入+或-或什么都不插入,使得计算结果总是 100 的程序,并输出所有的可能性。 例如:1 + 2 + 34 – 5 + 67 – 8 + 9 = 100
- 编写一个在1,2,…,9(顺序不能变)数字之间插入+或-或什么都不插入,使得计算结果总是100的程序,并输出所有的可能性。例如:1 + 2 + 34 – 5 + 67 – 8 + 9 = 100。
- 编写一个在1,2,…,9(顺序不能变)数字之间插入+或-或什么都不插入,使得计算结果总是100的程序,并输出所有的可能性。
- python实现线性表顺序存储的插入操作
- python ——使字典按添加顺序输出
- 45. 腾讯面试题: 使用hashmap 插入数据,怎么样按照插入数据的顺序输出数据
- Ordering guarantees in SQL Server...(SQLServer中保证排序不被优化,insert into ....select...order by时插入顺序不对)
- 顺序表的实现以及简单的 插入,删除,查找,输出操作
- C++实现顺序表的常用操作(插入删出查找输出)
- python json 按照输出顺序 loads输出
- 编写一个在1,2,…,9(顺序不能变)数字之间插入+或-或什么都不插入,使得计算结果总是 100 的程序,并输出所有的可能性
- 一、 启动4个线程,在控制台中输出数字,保证数字是按照顺序递增,并且没有重复数字,每隔1秒输出一个数字。
- python有顺序的字典OrderedDict
- python函数中输入关键字参数——字典参数,怎么样按输入的顺序输出
- oracle数据库并不保证sequence生成顺序与的数据插入顺序的保持一致。
- c#之站在IL语言角度彻底搞定HashTable输出的值和插入的时候顺序不一样
- Python按照书写顺序输出字典中的元素
- 文章标题编写一个在1,2,…,9(顺序不能变)数字之间插入+或-或什么都不插入,使得计算结果总是100的程序,并输出所有的可能性。
- Java-集合 list对象进行指定位置插入、删除、迭代、遍历输出(具体习题讲解)