Iterating over Dictionaries
You need to do something to each of the items in the dictionary in turn.
Use the for command to iterate over the keys of the dictionary:
>>> phone_numbers = {‘Simon’:’01234 567899′, ‘Jane’:’01234 666666′} >>> for name in phone_numbers: … print(name) … Jane Simon |
Discussion
There are a couple of other techniques that you can use to iterate over a dictionary. The following form can be useful if you need access to the values as well as the keys:
>>> phone_numbers = {‘Simon’:’01234 567899′, ‘Jane’:’01234 666666′} >>> for name, num in phone_numbers.items(): … print(name + ” ” + num) … Jane 01234 666666 Simon 01234 567899 |
See Also
All the recipes between Recipes 6.12 and 6.15 involve the use of dictionaries.
See the for command used elsewhere in Recipes 5.3, 5.21, 6.7, and 6.11.