You are here

Looping and dictionaries

4 September, 2015 - 14:38

If you use a dictionary in a for statement, it traverses the keys of the dictionary. For example, print_hist prints each key and the corresponding value:

def print_hist(h):
    for c in h:
        print c, h[c]

Here’s what the output looks like:

>>> h = histogram('parrot')>>> print_hist(h)a 1p 1r 2t 1o 1

Again, the keys are in no particular order.

Exercise 11.3.Dictionaries have a method called keys that returns the keys of the dictionary, in no particular order, as a list.

Modify print_histto print the keys and their values in alphabetical order.