Iam trying to do the exercises in the book “Learn Python the hard way” page: 106. The example is below:
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
I do not understand what cities['_find'] = find_city does? What is _find? In particular, why the underscore? Similarly, I am not sure what city_found = cities['_find'](cities, state) does. I have seen a similar post on the same question:
learn python the hard way exercise 40 help
which basically says that cities['_find'] = find_city adds the function find_city to the dictionary, but I still dont understand what city_found = cities['_find'](cities, state) does(?)
I’d really appreciate if someone could explain me the above two lines. Thanks for your time.
This code:
simply inserts the function
find_cityinto thecitiesdictionary, using the key_find. The underscore has no particular meaning, it’s just part of the key string. Probably chosen to not collide with actual city names.This code:
Calls the
find_cityfunction, by first looking it up in the dictionary using the_findkey.It could be rewritten as:
There doesn’t seem to be any real point in doing it like this, there’s no benefit in having the dictionary (which is called a “map” in the code) contain the
findfunction, that I can see.