I am following Zed Shaw's "Learn Python The Hard Way, 3rd Edition"
Here is a small code sample from exercise 39 of the book:
states = {
'Oregon': 'OR',
'Florida': 'FL',
'California': 'CA',
'New York': 'NY',
'Michigan': 'MI' }
for state, abbrev in states.items():
print "%s is abbreviated %s" % (state, abbrev)
print "-" * 10
for abbrev, state in states.items():
print "%s is abbreviated %s" % (abbrev, state)
The output of the above program is:
C:\>python code.py
California is abbreviated CA
Michigan is abbreviated MI
New York is abbreviated NY
Florida is abbreviated FL
Oregon is abbreviated OR
----------
California is abbreviated CA
Michigan is abbreviated MI
New York is abbreviated NY
Florida is abbreviated FL
Oregon is abbreviated OR
C:\>
In the code, no where we are telling python what are states and what are abbreviations. My question is: How come both print statements print the same? How does python display the appropriate "state" and "abreviation" even if I reverse the order in the second for loop?
How should i write the for loop if I want to show the abbreviation (value) first and then the (key).
Note: Thank you for your answer. Stackoverflow told me that in order to add anything to my question I should edit the question instead of adding a new comment....
stateorabbrevmean; you would have seen the same effect if you'd named those variablesfooandbar.