Question 6.15: Iterating over Dictionaries You need to do something to each......

Iterating over Dictionaries

You need to do something to each of the items in the dictionary in turn.

Step-by-Step
The 'Blue Check Mark' means that this solution was answered by an expert.
Learn more on how do we answer questions.

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.

Related Answered Questions

Question: 6.14

Verified Answer:

Use the pop command, specifying the key for the it...
Question: 6.11

Verified Answer:

Use the Python language feature called comprehensi...
Question: 6.12

Verified Answer:

Use a Python dictionary. Arrays are great when you...
Question: 6.13

Verified Answer:

Use the Python [] notation. Use the key of the ent...
Question: 6.10

Verified Answer:

Use the [:] Python language construction. The foll...
Question: 6.9

Verified Answer:

Use the sort Python language command: >>&...
Question: 6.7

Verified Answer:

Use the for Python language command: >>&g...
Question: 6.2

Verified Answer:

Use the [] notation to access elements of a list b...
Question: 6.3

Verified Answer:

Use the len Python function. For example: >&...