List order obtained by dictionary keys ()

Can keys () be expected to remain in the same order?

I plan to use them for a drop-down list, and I do not want them to change if I add or remove items from the dictionary.

+4
source share
6 answers

Ordering a key in a dict not guaranteed.

The documentation says:

It’s best to think of the dictionary as an unordered set of key: value pairs that require unique keys (in one dictionary) ...

The keys() dictionary method 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).

Python 2.7+ and 3.1+ have the OrderedDict class in collections as described by PEP 372 , which does exactly what you want. It remembers the order of adding keys:

 >>> from collections import OrderedDict >>> od = OrderedDict() >>> od[1] = "one" >>> od[2] = "two" >>> od[3] = "three" >>> od.keys() [1, 2, 3] 
+3
source

Not. According to the documentation :

Keys and values ​​are listed in random order, which is nonrandom, varies with Python implementations, and depends on the history of inserting and deleting dictionaries.

+5
source

Not. At least in cpython (and most likely in every other implementation) you definitely cannot . If you want a guaranteed order, an odict that guarantees order.

+1
source

No, not from one day to the next. keys () will be in random order (although I think they can be matched by instance lifetime, but this will not work for your menu).

Python3 ordered dictionaries: collections.OrderedDict documentation

+1
source

From python docs :

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

Thus, to solve this problem, you could sort the keys as soon as you β€œlist” them.

+1
source

You might want to try something like an array of dictionaries or objects. Arrays are ordered. The text for the menu item will be in any field of the array or object.

0
source

All Articles