Looping over unordered dictionary - why the same recall order?


#1

I know dictionaries are unordered, so I wasn't surprised when the items were ordered in a different way than in the dictionary. However, no matter how many times I run the code, it always returns the same sequence (apple cherry berry), which I find odd.
I've also changed the order of the items in the dictionary (which shouldn't make a difference of course, because the items are unordered) and got the exact same response (apple cherry berry).
Why doesn't an unordered dictionary result in a different sequence each time it is called?

My current code:

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

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

Output:

a apple
c cherry
b berry
None

#2

Hi, @batraaf,

A Python dictionary is a dict type, which is an example of a hash table. As part of the storage and retrieval process, the key of an item is translated into what is called a hash code. This process is very efficient and fast. Each unique hash code has a specific slot in memory designated for it, where items with that particular hash code are stored. When a program looks for an item in a dictionary, the hash code of the key is looked up, and the appropriate slot is searched for the item. It is possible for more than one key to translate to the same hash code. But typically, only a few items, at most, wind up in each slot, so if a given key is in the dictionary, it is found very quickly.

The most efficient algorithms for maintaining a hash table are ones that do not attempt to maintain keys in alphabetical or numerical order. In fact, such an order is not practical, since a single dictionary could contain keys of a mixture of different types.

When your program asks to print the entire dictionary, the Python interpreter simply goes through all the slots to output whatever is there, so the items might come out in the same order each time. So, while the dictionary makes no guarantee regarding the ordering of items, it also does not guarantee that the order will vary.

Priority is placed on efficiency of storage and retrieval; order is less important. If you want to control the order of retrieval of items in a dictionary, you can save the keys in a list, sort the list in some order, and use the list to get the keys in order to retrieve the items in the dictionary.

Here's an example:

d = {'e': 'elderberry', 'b': 'berry', 'd': 'dewberry', 'c': 'cherry', 'a': 'apple'}
keys = d.keys()
keys.sort()

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

Output:

a apple
b berry
c cherry
d dewberry
e elderberry

#3

Thank you, this was very insightful for me!