Deals Of The Week - hours only!Up to 80% off on all courses and bundles.-Close
Introduction
Dictionary basics
Dictionaries in loops and conditional statements
11. Iterating over dictionaries – items()
Dictionaries in functions
Summary

Instruction

Good job! Finally, there is also another function named items() that you can use to get both keys and values in convenient variables. Take a look:

phonebook = {'Mary': '8349374', 'Anne': '7439834', 'John': '3472983'}

for key, value in phonebook.items():
  print(key, '=', value)

Unlike phonebook.keys() and phonebook.values(), phonebook.items() returns key-value pairs. Take a look at the syntax in the for loop: we provided two variables after the for keyword, and we separated them with a comma. For each key-value pair in the dictionary, the key will be stored in the first variable (key), and the value will be stored in the second variable (value). You can of course name these variables anything you want, but key and value make the most intuitive sense.

Again, dictionaries are unordered data structures. Don't be surprised if the dictionary order changes at some point.

Exercise

Windows 1.0 was the first major operating system released by Microsoft (in 1985). For each system version in the dictionary, print the following sentence: {version_name} was released in {year} - {x} years after Windows 1.0.

Stuck? Here's a hint!

To calculate the number of years between a given Windows version's release and the release of Windows 1.0, use:

key - 1985