Skip to content Skip to sidebar Skip to footer

Learn Python The Hard Way - Exercise 39

On Exercise 39 of Learn Python The Hard Way, lines 37 to 39 look like this: print '-'*10 for state, abbrev in states.items(): print '%s has the city %s' % (state, abbrev) I th

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():

>>> forstate 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 indict: ... 
    

    which is equivalent to, but much faster than

    for k indict.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 indict.iterkeys(): ...
    
    for value indict.itervalues(): ...
    
    for key, value indict.iteritems(): ...
    

    This means that for x in dict is shorthand for for x in dict.iterkeys().

Solution 2:

This "missing link" between your first and second code snippet explains why they are equivalent:

print"-"*10for 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"