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:
cities['_find'] = find_city
simply inserts the function find_city into the cities dictionary, 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:
city_found = cities['_find'](cities, state)
Calls the find_city function, by first looking it up in the dictionary using the _find key.
It could be rewritten as:
city_found = find_city(cities, state)
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 find function, that I can see.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With