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


#1

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
None

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


#2

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


#3

@mtf

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)))

#4

How do we reconcile this?

NameError: name 'self' is not defined

#5

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