Looping Through all Key-Value Pairs:

  • Consider a new dictionary designed to store information about a user on a website.
python
1user0 = {
2'username': 'hbulldog',
3'first': 'harpua',
4'last': 'bulldog',
5}
  • Rather than accessing single pieces of information from a dictionary, we can use a for loop to see everything stored.
python
1user0 = {
2'username': 'hbulldog',
3'first': 'harpua',
4'last': 'bulldog',
5}
6
7for key, value in user0.items():
8    print("\nKey: " + key)
9    print("Value: " + value)
  • To write a for loop for a dictionary, as shown on line 7, you create names for the two variables that will hold the key and value in each key-value pair.
  • The second half of line 7 includes the name of the dictionary followed by the method, items(), which returns a list of key-value pairs.
    • Refresher on methods can be found in Unit 1.
  • In line 8, we use the variables to print each key, followed by the associated value in line 9.

Output:

1Key: username
2Value: hbulldog
3
4Key: first
5Value: harpua
6
7Key: last
8Value: bulldog

A Dictionary in a Dictionary:

  • You can nest a dictionary inside another dictionary too.
  • For example, if you have several cities, each with a unique city name, you can use the city names as the keys in a dictionary.
    • You can then store information about each city by using a dictionary as the value associated with the city name.
python
1cities = {
2    'Cullowhee': {
3        'country': 'USA',
4        'population': 15000,
5        'nearby mountains': 'Great Smokys',
6        },
7    'Asheville': {
8        'country': 'USA',
9        'population': 90000,
10        'nearby mountains': 'Pisgah Forest',
11        }
12    }
  • As we loop through the cities dictionary, Python stores each key in the first for loop variable and the dictionary associated with each city name goes in the second for loop variable.