Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Order of list obtained by dictionary's keys()

Tags:

python

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.

like image 507
Jesvin Jose Avatar asked Dec 20 '22 20:12

Jesvin Jose


2 Answers

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.

like image 140
BrenBarn Avatar answered Jan 03 '23 19:01

BrenBarn


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 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 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]
like image 29
Dave Webb Avatar answered Jan 03 '23 19:01

Dave Webb