-1

Why does the following program:

tokens = {
    'Apple': 1,
    'Orange': 2,
    'Pear': 3,
    'Banana': 4,
}

for t in tokens:
    print t, 'corresponds to', tokens[t]

Produce the following output:

Orange corresponds to 2
Pear corresponds to 3
Apple corresponds to 1
Banana corresponds to 4

In other words, why does it print the 2nd entry, then the 3rd, then the 1st, then the 4th? i.e. why does it not print from the 1st entry to the last?

  • 4
    possible duplicate of [Why is python ordering my dictionary like so?](http://stackoverflow.com/questions/526125/why-is-python-ordering-my-dictionary-like-so) – Robin Krahl Jan 22 '15 at 08:52
  • possible duplicate, but the chosen answer for the other question doesn't contain an example for how to work around it – sentiao Jan 22 '15 at 09:57

3 Answers3

1

From the python documentation entry for dict

"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."

That will be because the dict is implemented as a hash function which maps keys onto an arbitrarily-ordered but deterministic list

arbitrary because (1) the hash function is undocumented and (2) hashes mapping to the same entry in the list will (probably) be ordered according to their insertion order;

deterministic so that you always get the same value back.

foundry
  • 31,615
  • 9
  • 90
  • 125
1

A dict is not ordered, instead you may wish to use OrderedDict.

This will remember the order you add the keys.

from collections import OrderedDict
tokens = OrderedDict()

tokens['Apple'] = 1
tokens['Orange'] = 2
tokens['Pear'] = 3
tokens['Banana'] = 4
sentiao
  • 165
  • 9
jlb83
  • 1,988
  • 1
  • 19
  • 30
1

Alternatively to jlb83's answer you can loop over an ordered list of the keys, if you don't want to use OrderedDict.

tokens = {
    'Apple': 1,
    'Orange': 2,
    'Pear': 3,
    'Banana': 4,
}

for t in sorted(tokens.keys()):
    print t, 'corresponds to', tokens[t]

Produce the following output

Apple corresponds to 1
Banana corresponds to 4
Orange corresponds to 2
Pear corresponds to 3

I'm sure the sorting can be done in various ways, this works though.

sentiao
  • 165
  • 9