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
>>> 
20 Likes

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

2 Likes

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

19 Likes

Ah ok… makes sense, thank you.

2 Likes

Can I sort the dictionary using the values instead of keys?

Yes, it can be done. dict objects don’t have a .sort attribute (do they?) but we can use the built-in, sorted() and leverage the key attribute in the argument list. The key is to reduce your object to a list of some sort.

Simple,

obj = list(my_dict.items())

That gives us a list of tuple objects, key-value pairs. Python can unpack them on the fly as individual variables or we can use a lambda to extract one or the other.

>>> d = { 4: 4, 2: 2, 5: 5, 3: 3, 1: 1 }
>>> l = list(d.items())
>>> l
[(4, 4), (2, 2), (5, 5), (3, 3), (1, 1)]
>>> m = sorted(l, key=lambda x: x[1])
>>> m
[(1, 1), (2, 2), (3, 3), (4, 4), (5, 5)]
>>> 
```.
6 Likes

As of Python 3.6 dictionaries are ordered now.

3 Likes

Since dictionaries are ordered now, this forum could be deleted, so we do not lose time reading it.
Fran <3

2 Likes

I’m using Python 3.10.6 and the result is unordered.

Ordered doesn’t mean sorted.

I am assuming you created a dictionary like this:

sensors = {'living room': 21, 'kitchen': 23, 'bedroom': 20, 'pantry': 22}

In your screenshot, the dictionary appears exactly in the order that you created it.

In earlier versions of Python, dictionaries were unordered i.e. if you printed or looped over a dictionary, the order you see may be different than the one in which you created/inserted the items.

I clicked multiple times on Run button, but it gave the results printed the same way it’s defined.