The order of elements in dictionaries

Screenshot 2021-01-01 141952

Why is in print( d_3 ) output the key_value pair ( 2: ‘two’ ) the last in the dictionary? I think it should be the first the same as its order in the original dictionary d_3.

And in d_2 why was 0 in ( 0: ‘zero’ ) converted to False in print d_2? I have understood that only boolean values ( True & False ) are converted to 1 & 0 in dictionaries when they are keys of a dictionary.

Good observation!

In the Python version used by Dataquest, dictionaries are unordered. So, the output order can be different than the one you coded.

Yes, I think this might be a mistake in the content.

An odd “gotcha” is when we mix integers with Booleans as dictionary keys. The hash() command converts the Boolean True to 1, and the Boolean False to 0. This means the Booleans True and False will conflict with the integers 0 and 1. The dictionary keys won’t be unique anymore, and Python will only keep the last key-value pair in cases like that.

Based on some quick experimentation, in the case of such a clash, it takes the first key and the last value instead of the last key-value pair mentioned in the Mission Step. (cc - @Sahil)

Note: Please make sure to include the Mission/Mission Step link in your future posts as well.


I’ve really forgotten to include the mission link, I am sorry.
Thanks a lot for the clarification.
What Python version do we use?

1 Like

Hi @the_doctor,

This is no longer a problem as we are using Python 3.8.2. From 3.6, the dictionary follows the order of insertion.

@Maho, you can check out the python version on any platform by running the following code:

import platform

@the_doctor, you are right, whenever there is a conflict, python replaces the first conflicting key’s value with the second conflicting keys value. I will get it logged for correction.


1 Like