What is an expanded for loop?

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!

Related Course: Complete Python Programming Course & Exercises

Expanded For Loop

Given a dictionary with a one to one mapping we simply iterate over each item and print the key and value. We use the dictionaries method .items() which contains all items.

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():
print('Acronym: %s. State = %s ' % (key,value))

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.

Download exercises