OrderedDict does not preserve the order

久未见 提交于 2019-11-29 07:38:01

By putting the items in a (non-ordered) dict and constructing the OrderedDict from that, you've already discarded the original order. Construct the OrderedDict from a list of tuples, not a dict.

Please find code snippet below

>>> from collections import OrderedDict
>>> listKeyVals = [(1,"One"),(2,"Two"),(3,"Three"),(4,"Four"),(5,"Five")]
>>> x = OrderedDict(listKeyVals)
>>> x
OrderedDict([(1, 'One'), (2, 'Two'), (3, 'Three'), (4, 'Four'), (5, 'Five')])
>>> 

I suggest you to vist examples from my article

https://techietweak.wordpress.com/2015/11/11/python-collections/

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!