Why aren't dictionaries printed in the same order as they are created?

More out of curiosity than a real problem… Why does the terminal print the dictionary differently than it is written in the compiler?

Compiler:
…sensors = {“living room”: 21, “kitchen”: 23, “bedroom”: 20, “pantry”: 22}…

printed:
{‘bedroom’: 20, ‘pantry’: 22, ‘living room’: 21, ‘kitchen’: 23}

At first I thought there had been some sorting applied before printing, but I can’t figure out any sorting logic behind the printed version.

Dictionaries, like Ruby hashes and JS objects have no set insertion order. They are said to be unordered. The Collections library has an OrderedDict class, but that won’t be necessary in this course to use.

If you want to set the order the dictionary prints, such as sorted, then iterate over a sorted list of keys, and poll their values in the dictionary.

>>> for key in sorted(sensors.keys()):
    print ('{}: {}'.format(key, sensors[key]))

    
bedroom: 20
kitchen: 23
living room: 21
pantry: 22

This will also work, but is less explicit…

>>> for key in sorted(sensors):
    print ('{}: {}'.format(key, sensors[key]))

    
bedroom: 20
kitchen: 23
living room: 21
pantry: 22
>>> 
2 Likes

I tried out your code, the output doesn’t get jumbled up. Fail to understand why it got jumbled up for you.

Because previous to Python 3.7 dictionary insertion order was not retained. The version you are testing with may be a newer one.

1 Like

Ah ok… makes sense, thank you.

1 Like