Python

Expanded For Loop

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? a dictionary can also be used in a loop too!

Related Courses Complete Python Bootcamp: Go from zero to hero in Python

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.

states = {
'NY': 'New York',
'ME': 'Maine',
'VT': 'Vermont',
'TX': 'Taxas',
'LA': 'Los Angeles'
}

for key, value in states.items():
print('Acronym: %s. State = %s ' % (key,value))

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

What is going on? we used an expanded for loop. We use both key and value through the dictionary states.

Previous Post Next Post

Cookie policy | Privacy policy | ©