i’m reading zed shaw’s book “learning python the hard way”. Forgive me but i’m a newbie in coding, and i’m having a hard time understanding this. I can’t seem to see how find_city function finds out what city to be returned by entering the state. The lines with” okay pay attention” and” # this line is the most important ever! study! are the ones confusing me.
cities = {'CA': 'San Francisco', 'MI': 'Detroit',
'FL': 'Jacksonville'}
cities['NY'] = 'New York'
cities['OR'] = 'Portland'
def find_city(themap, state):
if state in themap:
return themap[state]
else:
return "Not found."
# ok pay attention!
cities['_find'] = find_city
while True:
print "State? (ENTER to quit)",
state = raw_input("> ")
if not state: break
# this line is the most important ever! study!
city_found = cities['_find'](cities, state)
print city_found
Briefly:
citiesis instantiated as a dictionary, and some key/value are inserted here. Both key and values are string for CA -> San Francisco, MI -> Detroit, etc. etc.a function named
find_cityis defined, it takes two input parameters (themapandstate);to the
citiesdictionary is added another key/value, where key is the string ‘_find’ but, this time, the value is the function find_city and not a string as before;in the line
city_found = cities['_find'](cities, state)you ask to the dictionarycitiesthe value associated to the key ‘_find’, that is the functionfind_city. Then, this function is called with the dictionary itself as first parameter and the ‘state’ read by the stdin as second parameter.It would have been the same if it was written as:
HTH