Storing Python dictionary entries in the order the

2019-01-18 03:28发布

问题:

This question already has an answer here:

  • Dictionaries: How to keep keys/values in same order as declared? 10 answers

Fellows:

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'}

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

Any thoughts?

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

回答1:

Try python 2.7 and above, probably 3.1, there is OrderedDict

http://www.python.org/

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

PEP 372: Adding an ordered dictionary to collections



回答2:

Use a list to hold the key order



回答3:

Implementations of order-preserving dictionaries certainly do exist.

There is this one in Django, confusingly called SortedDict, that will work in Python >= 2.3 iirc.



回答4:

Dictionaries in Python are implemented as hash tables, which is why the order appears random. You could implement your own variation of a dict that sorts, but you'd lose out on the convenient syntax. Instead, keep track of the order of the keys, too.

Initialization:

keys = []
myDict = {}

While reading:

myDict[key] = value
keys.append(key)

While writing:

for key in keys:
  print key, myDict[key]


回答5:

Rather Than Explaining The Theoretical Part I'll Give A Simple Example.

>>> from collections import OrderedDict
>>> my_dictionary=OrderedDict()
>>> my_dictionary['foo']=3
>>> my_dictionar['aol']=1
>>> my_dictionary
OrderedDict([('foo', 3), ('aol', 1)])


回答6:

There is a very short answer to that.. do this--

dictCopy=yourdictname.copy()

then use the dictCopy , it will be in the same order.