Looping over a dictionary: Order Question


#1

My code is as follows:

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

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

The tutorial link is:

The list is defined as:
'a': 'apple', 'b': 'berry', 'c': 'cherry'

But the console print out is:

a apple
c cherry
b berry

Why isn't it:

a apple
b berry
c cherry


#2

Hi @gigajumper47743 ,

Python dictionaries are implemented as hash tables, which are unordered.

If you ever need to control the order in which items in a dictionary are processed, you could save the keys in a sequence such as a list, stored in the order that you want, and then use the sequence to access the dictionary keys in the desired order.

For lots of information, see Wikipedia: Hash table.


#3

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