按照它们被推送的顺序存储Python字典条目 [英] Storing Python dictionary entries in the order they are pushed
问题描述
研究员:
Python字典没有特定的顺序存储(映射没有顺序),例如
A Python dictionary is stored in no particular order (mappings have no order), e.g.,
>>> myDict = {'first':'uno','second':'dos','third':'tres'}
myDict = {'first':'uno','second':'dos','third':'tres'}
>>> myDict
myDict
{'second': 'dos', 'third': 'tres', 'first': 'uno'}
虽然可以从字典中检索排序列表或元组,但我想知道是否可以使字典按照传递给它的顺序存储项目在前面的例子中,这意味着内部排序为 {'first':'uno','second':'dos','third':'tres'}
并没有什么不同。
While it is possible to retrieve a sorted list or tuple from a dictionary, I wonder if it is possible to make a dictionary store the items in the order they are passed to it, in the previous example this would mean having the internal ordering as {'first':'uno','second':'dos','third':'tres'}
and no different.
我需要这个,因为我正在使用字典来存储从配置文件中读取的值;一旦读取和处理(值被更改),它们必须按照读取的顺序写入新的配置文件(此顺序不是字母顺序或数字)。
I need this because I am using the dictionary to store the values as I read them from a configuration file; once read and processed (the values are altered), they have to be written to a new configuration file in the same order as they were read (this order is not alphabetical nor numerical).
任何想法?
修改:
请注意,我不是寻找辅助方式来检索订单像列表一样),但是使字典本身被排序的方式(就像在将来的Python版本)。
Edit: Please notice that I am not looking for secondary ways to retrieve the order (like lists), but of ways to make a dictionary be ordered in itself (as it will be in upcoming versions of Python).
推荐答案
p>尝试python 2.7及以上,大概3.1,有OrderedDict
Try python 2.7 and above, probably 3.1, there is OrderedDict
http://python.org/download/releases/2.7/
>>> from collections import OrderedDict
>>> d = OrderedDict([('first', 1), ('second', 2),
... ('third', 3)])
>>> d.items()
[('first', 1), ('second', 2), ('third', 3)]
这篇关于按照它们被推送的顺序存储Python字典条目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!