Why doesn’t the code just print out in order that it is written in the dictionary?


#1

In the activity I have the following code:
d = {‘a’: ‘apple’, ‘b’: ‘berry’, ‘d’: ‘doughnut’, ‘e’: ‘ele’, ‘c’: ‘cherrys’}

for key in d:

Your code here!

print key + " " + d[key]

I was wondering, regardless of where the key ‘c’ is placed in the dictionary, it always seems to print out second in the consul. Is there a reason for this? Why doesn’t the code just print out in order that it is written in the dictionary?
How do dictionaries store / arrange keys?


FAQ: Learn Python- Loops - Looping over a dictionary
#2

Ordinary dictionaries are not ordered. That means the insertion order is not remembered. If it is important to retain original insertion order then use the OrderedDict class of the collections module.


There are many ways to induce order, one of which is sorting the keys.

>>> d = {'a': 'apple', 'b': 'berry', 'd': 'doughnut', 'e': 'ele', 'c': 'cherrys'}
>>> d
{'d': 'doughnut', 'e': 'ele', 'b': 'berry', 'c': 'cherrys', 'a': 'apple'}
>>> sorted(d)
['a', 'b', 'c', 'd', 'e']
>>> 

So if output order is important, in this case alphabetized keys, then use the sorted keys to poll the dictionary.

>>> for x in sorted(d):
    print (x, d[x])

    
a apple
b berry
c cherrys
d doughnut
e ele
>>> 

This is just scratching the surface so keep up your study of this module and research it in review to learn of the variety of sorting and ordering methods that are available.


#3

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