14/19 Order of a dictionary


Her is my code:
d = {‘a’: ‘apple’, ‘b’: ‘berry’, ‘c’: ‘cherry’}

for key in d:

Your code here!

print key, d[key]

and her is the result
a apple
c cherry
b berry

is this order normal? I was expecting a print out with the order of keys


Why? Dictionaries are accessed by key, not by index. So they don’t have to ordered.


Hm. I don’t seem to understand this one myself. What would make the keys be printed in this fashion? It would seem like even though this isn’t organized by index, it is strange that it seems to be printing backwards almost, a,c,b,a,c,b style. It’s almost like it’s negatively incrementing for some reason. I would also expect without implicitly defining to print by -1 that it would print:

  • a apple
  • b berry
  • c cherry


python is written in C, to understand the answer to this question would require you to understand the implementation of the underlying implementation of the hashtable, which is something i wouldn’t waste much energy on unless you really have to


Dictionaries do not remember the order of data point insertion. Data is not inserted sequentially as it would be to an indexed list.

There is a module, collections that includes an OrderedDict method for tracking the order of insertion.



That’s the point !

Thank you


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