Why for loop works in this order for dictionary?


#1

https://www.codecademy.com/courses/learn-python/lessons/loops/exercises/looping-over-a-dictionary?action=lesson_resume

When I run below code, output is as follows:
a apple
c cherry
b berry

My question is, why c comes earlier then b?
Is there any rule for this?

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

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

#2

Hi @codepro28030,

A dict object is unordered, meaning that the items within it are not considered to be in any particular order, regardless of when they were created. However, you may control the order of output, if you wish, by sorting the keys, as follows …

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

for key in sorted(d.keys()):
    print key + " " + d[key]

Output …

a apple
b berry
c cherry
d dewberry

#3

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