Skip to main content
Stack Overflow
  1. About
  2. For Teams

Return to Revisions

3 of 3
Commonmark migration

You just look at two lines from your code:

  1. cities['_find'] = find_city

  2. city_found = cities['find'](cities, state)

Explanation for (1):

As cities is dictionary before you use cities['_find']. print it...

print(cities)
Output: {'CA': 'San Francisco', 'MI': 'Detroit', 'FL': 'Jacksonville', 'NY': 'New York', 'OR': 'Portland'} 

Now after using cities['_find']=find_city,

print(cities) 
Output: {'CA': 'San Francisco', 'MI': 'Detroit', 'FL': 'Jacksonville', 'NY': 'New York', 'OR': 'Portland', *'_find': <function find_city at 0x01BAB738*>}
 

Here the last dictionary item is added with key _find and the value is the function find_city.

Explanation for (2):

Now city_found = cities['find'](cities, state)

Now we know that find_city is in the dict at _find, that means we can do work with it. The it can be broken down like this:

  1. Python sees city_found = and knows we want to make a new variable.

  2. It then reads cities and finds that variable, it’s a dict.

  3. Then there’s ['_find'] which will index into the cities dict and pull out whatever is at _find.

  4. What is at ['_find'] is our function find_city so Python then knows it’s got a function, and it does the function call.

  5. The parameters cities, state are passed to this function find_city, and it runs because it’s called.

  6. find_city then tries to look up states inside cities, and returns what it finds.

  7. Python takes what find_city returned, and finally that is what is assigned to city_found.

AltStyle によって変換されたページ (->オリジナル) /