Python Dictionary Creation Autosort


#1

So can anyone shed light on the fact that when I’m making a dictionary in python in the codecademy editor, the dictionary’s key:value pairs are not in the same order as the lists themselves?

Also, every time I update a dictionary by adding a key:value pair, the printed version of the dictionary just seemingly randomly switches orders of the key:value pairs.

Example:

list_a = [a, b, c, d]
list_b = [1, 2, 3, 4]

dictionary = {key:value for key, value in zip(list_a, list_b)
print(dictionary)

I would expect this:

dictionary = {a:1, b:2, c:3, d:4}

But it produces:

dictionary = {b:2, c:3, a:1, d:4}


#2

Standard dictionary objects are not ordered. The insertion order is not recorded.

Since dictionaries are essentially look-up tables and all keys are unique, the order is not needed. Poll a key and get its value.


#3

So what I’m understanding is that since order is irrelevant, as opposed to lists, the printout would be different every time you printed it?


#4

Yes, it may appear in any order.

Python has a library module called collections that includes the class, OrderedDict..

If you don’t want to use the library but wish to output a sorted dictionary, then sort the keys…

for x in sorted(dictionary):
    print (x, dictionary[x])

#5

Thanks a bunch, @mtf!