Looping over a dictionary


#1



https://www.codecademy.com/en/courses/python-beginner-en-cxMGf/2/1?curriculum_id=4f89dab3d788890003000096#


I'm not getting an error message but I'm wondering why my for loop doesn't print the dictionary items in order. It prints a apple then c cherry then b berry


Why doesn't it print them in the order that they are contained in the dictionary?


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

for key in d:
    print key + " " + d[key]# Your code here!


#2

Because dictionaries are unordered, meaning they don't remember the order in which they are written to.

If the order of representation is required to be alphabetical or sequential then an index is required, a key index.

>>> d = {'a': 'apple', 'b': 'berry', 'c': 'cherry'}
>>> k = list(d.keys())
>>> k
['c', 'b', 'a']
>>> k.sort()
>>> k
['a', 'b', 'c']
>>>

Now if we iterate over k, we always get the same order.

>>> for key in k: print (key, d[key])

a apple
b berry
c cherry
>>>

#4

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