I recently published an article about iterating over ranges and another one about iterating over the indices of a sequence. Feel free to read them both if you haven’t yet.
And today we’ll learn how to iterate over the keys and values of a dictionary.
Iterating over Keys
We can easily iterate (i.e. step from one to the next over all the elements) over the keys of the dictionary using the for loop:
>>> best_scores = {"Mary" : 123, "Richard" : 116, "Cindy" : 142}
>>> for key in best_scores:
... print(key)
...
Mary
Richard
Cindy
Alternatively, we can use the method keys:
>>> for key in best_scores.keys():
... print(key)
...
Mary
Richard
Cindy
Iterating over Values
If you want to iterate over the values, there’s the values method:
>>> for value in best_scores.values():
... print(value)
...
123
116
142
You can achieve the same result without the values method, although this way is less efficient. You can do it like so:
>>> for key in best_scores:
... print(best_scores[key])
...
123
116
142
And just one more example:
>>> cities = {"Stuttgart" : "Germany", "Montevideo" : "Uruguay", "Perth" : "Australia", "Luxor" : "Egypt"}
>>> for city in cities:
... print("{} is situated in {}.".format(city, cities[city]))
...
Stuttgart is situated in Germany.
Montevideo is situated in Uruguay.
Perth is situated in Australia.
Luxor is situated in Egypt.
In this example the loop variable is set to “Stuttgart” in the first iteration, then to “Montevideo” and to the other keys one by one in each iteration that follows.
Iterating over Key-Value Pairs
You can use the for loop with dictionaries to get both the keys and the values. You need the items method:
>>> prices = {"cheese" : 2.48, "milk" : 1.85, "butter" : 3.69}
>>> for k, v in prices.items():
... print("{} : {}".format(k,v))
Here k and v stand for keys and values respectively. Here’s the output:
cheese : 2.48
milk : 1.85
butter : 3.69