Key Order in Python Dictionaries

the code:

d = {'a': 0, 'b': 1, 'c': 2} l = d.keys() print l 

It prints ['a', 'c', 'b']. I'm not sure how to method determines the order of keywords within l . However, I would like to be able to retrieve keywords in the “correct” order. The correct order, of course, will create the list ['a', 'b', 'c'].

+48
python dictionary
Apr 12 2018-11-11T00:
source share
5 answers

You can use OrderedDict (Python 2.7 required) or higher.

Also note that OrderedDict({'a': 1, 'b':2, 'c':3}) will not work, since the dict created with {...} has already forgotten the order of the elements. Instead, you want to use OrderedDict([('a', 1), ('b', 2), ('c', 3)]) .

As mentioned in the documentation, for versions below Python 2.7 you can use this recipe.

+50
Apr 12 2018-11-11T00:
source share
 >>> print sorted(d.keys()) ['a', 'b', 'c'] 

Use a sorted function that sorts the passed iterator.

The .keys() method returns keys in random order.

+32
Apr 12 2018-11-11T00:
source share

Of the dictionaries, Python 3.6 on supports the default insertion order . However, saving the order is not yet “guaranteed” (it will probably be in 3.7):

The aspect of preserving the order of this new implementation is considered, the implementation details should not be relied upon (this may change in the future, but it is advisable that this new voice recorder implementations in the language for several releases before changing the language specification for the mandatory preservation semantics for all current and future Python implementations; it also helps maintain backward compatibility with older versions of the language, where random iteration is still valid, e.g. Python 3.5).

So now you should use collections.OrderedDict if you want to have an ordered dictionary.

+11
Oct 12 '16 at 19:51
source share

Just sort the list if you want to use it.

 l = sorted(d.keys()) 
+10
Apr 12 2018-11-11T00:
source share

From http://docs.python.org/tutorial/datastructures.html :

"The keys () method of a dictionary object returns a list of all the keys used in the dictionary in random order (if you want it to be sorted, just apply the sorted () function to it).

+8
Apr 12 2018-11-11T00:
source share



All Articles