For loop over dictionary to print keys and values: random order of elements?


When I loop over the dictonary the order of the items printed is not the same as the order of the dictionary. What logic is the for-loops going through dictionaries with?

My code is:

d = {'a': 'apple', 'b': 'berry', 'c': 'cherry'}

for key in d:
# Your code here!
print key +' ' + d[key]

which prints:

a apple
c cherry
b berry

During the loop cherry and berry has changed places compared to the original dictionary. Why does this happen?


It happens because of the nature of dictionaries which are unordered owing that they have string indices that can be written in any order. Dictionaries are not like lists, which have numerical indices that are ordered from 0 to len(the_list).



That is true to a point but there is this very nice module that you can use to order your dicts and conveniently it is called

from collections import OrderedDict

You then use it like

grid = {(x, y): '~Water' for y in range(1, 11) for x in range(1, 11)}
printable_board = OrderedDict(sorted(grid.items()))
for y in range(1, 11):
    print(' '.join(str(printable_board[x, y])[0] for x in range(1, 11)))


How do we reconcile this?

NameError: name 'self' is not defined


Fixed it, thought I got all the class code out.