A normal for loop over a dictionary gives you the keys only. An expanded for loop uses dict.items() and gives you the key and the value together, which is what you want most of the time.
We’ve seen simple numerical for loops before. For numerical lists these type of for loops well.
What if we use a dictionary? Recall, a dictionary is a group of key, value pairs. In Python, a dictionary can also be used in a loop too!
Expanded For Loop
With a dictionary you can get the key and the value in one loop.
First define the dictionary:states = {
'NY': 'New York',
'ME': 'Maine',
'VT': 'Vermont',
'TX': 'Taxas',
'LA': 'Los Angeles'
}
Then iterate over the same dictionary, you can use this type of loop instead:
for key, value in states.items(): |
For this dictionary this will output:
Acronym: NY. State = New York
Acronym: ME. State = Maine
Acronym: VT. State = Vermont
Acronym: TX. State = Taxas
Acronym: LA. State = Los Angeles
But it can be used with any Python dictionary.
What is going on?
We used an expanded for loop. The loop uses both key and value through the dictionary states. It in turn outputs both the key and value for each pair.
The forms
- For only the keys:
for key in d: - For key and value:
for key, value in d.items(): - For only the values:
for value in d.values(): - With the position added:
for i, (key, value) in enumerate(d.items()):
You can loop two lists at the same time with
for a, b in zip(list_a, list_b):, and that stops at the shorter list.
To get the keys in sorted order use sorted(d) inside the loop, since a
dictionary keeps no order of its own.
Want more practice on this? Practise this on PyChallenge, there are short browser exercises you can run right after reading.
