Using a for loop to print dictionary entries

advertisements

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?


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.