I know that normally the order of keys/values in a dictionary is arbitrary. However, if you declare a dictionary “longhand” (see below) and then never add or remove any keys, does this mean that the key order will be kept as you declared it?
I’ve done a couple of brief experiments and the answer seems to be Yes, but before I count on this, I wanted to make sure.
When I say “longhand”, I just mean an explicit declaration of each key & value all at a shot:
myDict = {key1: val1, key2: val2, key3: val3, .... }
Dictionaries are inherently unordered in Python. Use
collections.OrderedDictif you want to preserve ordering. Note thatcollections.OrderedDictpreserves insertion order.Also, a counterexample to the notion that keys are kept in declaration order:
Dictionary keys also need not be sorted:
So, don’t ever rely on the order of a dictionary’s keys unless you know it’s an
OrderedDict.