Quick question about print order


#1



Why does the print order not go from a to b to c?


The code prints:
a apple
c cherry
b berry


I expected it to print as follows:
a apple
b berry
c cherry


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

for key in d:
    print key, d[key]


#2

A dictionary is natively unordered (in other words, it does not remember the order in which items were inserted). It cannot be predicted what order it will print in. It won't come up here but there is some reading you could do on the collections module once you get further along. It contains a dictionary subclass called 'OrderedDict` which when implemented does retain the order of insertion.


#3

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.