1

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, .... }
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
JDM
  • 1,709
  • 3
  • 25
  • 48
  • While it is likely they will not change ordering, it is not guaranteed. Why would you need to rely on the order being constant? – bplattenburg Jan 30 '13 at 20:50
  • @MartijnPieters, thanks -- I missed that one when searching previous threads. – JDM Jan 31 '13 at 01:26
  • @bplattenburg, I'm setting up the framework behind a Tkinter GUI and was a considering a dictionary as a way to store the labels & values for a collection of radiobuttons. There's more to the story of course on why I want to do *that*, but that's the answer to your question. – JDM Jan 31 '13 at 01:26

1 Answers1

11

Dictionaries are inherently unordered in Python. Use collections.OrderedDict if you want to preserve ordering. Note that collections.OrderedDict preserves insertion order.

Also, a counterexample to the notion that keys are kept in declaration order:

>>> {1:2, 4:5, 2:3}
{1: 2, 2: 3, 4: 5}

Dictionary keys also need not be sorted:

>>> {-1:-1, -2:-2, 1:1}
{1: 1, -2: -2, -1: -1}

So, don't ever rely on the order of a dictionary's keys unless you know it's an OrderedDict.

nneonneo
  • 171,345
  • 36
  • 312
  • 383