Can I expect the keys() to remain in the same order?
I plan to use them for a dropdown box and I dont want them to shift if I add or delete items from the dictionary.
No. According to the documentation:
Keys and values are listed in an arbitrary order which is non-random, varies across Python implementations, and depends on the dictionary’s history of insertions and deletions.
The ordered of the keys in a dict
is not guaranteed.
The documentation says:
It is best to think of a dictionary as an unordered set of key: value pairs, with the requirement that the keys are unique (within one dictionary)...
The
keys()
method of a dictionary object returns a list of all the keys used in the dictionary, in arbitrary order (if you want it sorted, just apply thesorted()
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 in which keys were added:
>>> from collections import OrderedDict
>>> od = OrderedDict()
>>> od[1] = "one"
>>> od[2] = "two"
>>> od[3] = "three"
>>> od.keys()
[1, 2, 3]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With