Learn Python The Hard Way - Exercise 39
Solution 1:
states is a dictionary, so when you called for test in states.items() it assigns each item of the dictionary (a tuple) to test.
Then you are just iterating over the items and printing their keys and values as you would with for state, abbrev in states.items():
>>> for state in states.items():
print (state) # print all the tuples
('California', 'CA')
('Oregan', 'OR')
('Florida', 'FL')
('Michigan', 'MI')
('New York', 'NY')
All the details are available online, for instance in PEP 234 -- Iterators under Dictionary Iterators:
Dictionaries implement a tp_iter slot that returns an efficient iterator that iterates over the keys of the dictionary. [...] This means that we can write
for k in dict: ...which is equivalent to, but much faster than
for k in dict.keys(): ...as long as the restriction on modifications to the dictionary (either by the loop or by another thread) are not violated.
Add methods to dictionaries that return different kinds of iterators explicitly:
for key in dict.iterkeys(): ... for value in dict.itervalues(): ... for key, value in dict.iteritems(): ...This means that
for x in dictis shorthand forfor x in dict.iterkeys().
Solution 2:
This "missing link" between your first and second code snippet explains why they are equivalent:
print "-"*10
for test in states.items():
state, abbrev = test
print "%s has the city %s" % (state, abbrev)
Post a Comment for "Learn Python The Hard Way - Exercise 39"