Reputation: 23078
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.
Upvotes: 4
Views: 143
Reputation: 193696
The ordered of the keys in a dict
is not guaranteed.
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]
Upvotes: 3
Reputation: 5555
From python docs:
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 the sorted() function to it).
So a way to solve this issue would be to sort the keys as soon as you "listify" them.
Upvotes: 1
Reputation: 1502
You may want to try something like an array of dictionaries or objects. Arrays are ordered. The text for the menu item would be in some field of the array or object.
Upvotes: 0
Reputation: 54
No, not from one day to the next. keys() will be in an arbitrary order (although I think they might be consistent over the instance's lifetime, but that won't work for your menu).
Python3 has ordered dictionaries: collections.OrderedDict documentation
Upvotes: 1
Reputation: 154484
No. At least in cpython (and most likely every other implementation) you definitely can't. If you want guaranteed order, check out odict
, which does guarantee order.
Upvotes: 1
Reputation: 251373
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.
Upvotes: 5