For Loops II
In the last article, you used a for
loop to iterate through lists. The for
loop can be applied to numerous other iterables. Most notably, the for
loop can be used to iterate through dictionaries!
Recall that dictionaries are a collection of {key: value}
pairs.
{key: value, key: value, key: value}
In this article, you will learn how to use a for
loop to iterate through a simple dictionary.
The skeleton for iterating through dictionaries is as follows:
for (key, value) in dictionary.items():
//iterates through each (key, value) pair
Iterating through a dictionary
You will iterate through a dictionary of two {key: value}
pairs
movies = { 'Titanic': 1997, 'Finding Nemo': 2003 }
Using the skeleton for iterating through dictionaries, you can print the {key, value}
pair at each iteration.
for (key, value) in movies.items():
print(key, value)
>>Titanic 1997
>>Finding Nemo 2003
We can get super fancy and format the code to print a full sentence at each iteration
for (key, value) in movies.items():
print('The movie {}, was made in {}'.format(key, value))
>>The movie Titanic, was made in 1997
>>The movie Finding Nemo, was made in 2003
format
replaces each argument {}
in the String with its corresponding variable.
This wraps up for
loops! In summary, a for
loop will keep executing the same block of code until it has iterated through the entire iterable (whether it's a list, dictionary or tuple). This begs the question, what is the difference between a for
loop, and a while
loop? Find out in the next article!