Think Python for CS114

Chapter 24 Looping through dictionaries

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: dict[any, any]) -> None:
    for c in h:
        print(c, h[c])

Here’s what the output looks like:

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

Since Python 3.7, the keys are in the order they were inserted. But we should not rely on this order. To traverse the keys in sorted order, you can use the built-in function sorted:

>>> for key in sorted(h):
        print(key, h[key])
a 1
o 1
p 1
r 2
t 1