-3

If you look at the following code:

examples = {"Main 1": "blabla", "Main 2": "test", "Main 3": "ya", "Main 4": "ha", "Main 5": "no", "Main 6": "blabla", "Main 7": "test", "Main 8": "ya", "Main 9": "ha", "Main 10": "no", "Main 11": "blabla", "Main 12": "test", "Main 13": "ya", "Main 14": "ha", "Main 15": "no", "Main 16": "boo", "Main 17": "blabla", "Main 18": "test", "Main 19": "ya", "Main 20": "ha", "Main None": "None",}

for example in examples.keys():
    print example

It prints the following:

Main 1
Main 14
Main 3
Main 2
Main 5
Main 4
Main 7
Main 6
Main 9
Main 8
Main None
Main 12
Main 19
Main 17
Main 18
Main 16
Main 13
Main 15
Main 20
Main 11
Main 10

How do I make it preserver the dict order so that it goes 1, 2, 3, 4, 5, 6, 7...etc

Ryflex
  • 5,559
  • 25
  • 79
  • 148
  • 5
    Python dictionaries *are not ordered*. You cannot preserve the initial ordering; use `collections.OrderedDict()` instead. – Martijn Pieters Apr 29 '14 at 17:00
  • the alternative is to sort your keys; a natural sort would be required though. – Martijn Pieters Apr 29 '14 at 17:01
  • 1
    A quick search for "sorted dictionary python" or "ordered dictionary python" returns https://docs.python.org/2/library/collections.html. Please refer to "Search, and research" section of http://stackoverflow.com/questions/how-to-ask – IceArdor Apr 29 '14 at 17:04
  • 1
    Last but not least, the `.keys()` call is redundant; you can loop directly over a dictionary and still get keys: `for example in examples:`. – Martijn Pieters Apr 29 '14 at 17:08

1 Answers1

1

Ordinary dictionaries are constructed from a hash table and do not preserve ordering. Use OrderedDict from the standard library collections module instead.

Andrew Gorcester
  • 19,595
  • 7
  • 57
  • 73