14/19 Why does my code output in this order?


#1

My code for exercise 14 is

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

for key in d:
  print key, d[key]

and prints out
a apple
c cherry
b berry

Why does it print in this order, and not in the order of the keys in the dictionary?


#2

Because dictionaries do not remember the order they are created. They are unordered.


#3

So why does it print as a, c, b each time? If the for loop is looking at keys in the dictionary, does it do it randomly?


#4

Not so much randomly, but in any order. The main thing is that when iterating a dictionary, every key is iterated.

Dictionaries are lookup tables with string indices (keys).

dictionary[key] == value

It is not important for them to have any order since they are essentially a set.


#5

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.