How to understand code of "Exercise 40: Dictionaries .." in Learn Python The Hard Way

Question:

I’m trying to follow along with Exercise 40 from Learn Python The Hard Way, 2nd edition", by Zed A. Shaw.

The last snippet of code sets up two dictionaries like so:

states = {
'Oregon': 'OR',
'Florida': 'FL',
'California': 'CA',
'New York': 'NY',
'Michigan': 'MI'
}
cities = {
'CA': 'San Francisco',
'MI': 'Detroit',
'FL': 'Jacksonville'
}

and then does various things with the dictionary.

I don’t understand what is happening at this point in the example:

print "Michigan has: ", cities[states['Michigan']]

When I try it, the result is Michigan has: Detroit.

Why? How does Python link one dictionary with the other?

This is my assumption and understanding I want to verify:

Python reads cities[states['Michigan']] backwards. First, it looks through the states and finds Michigan, then its value. Next it uses this value to look in cities, where the value from the state is the key. Finally it prints out the value for the key from cities.

Why does it not just print out the key from the cities (MI)?

Asked By: Loki

||

Answers:

Python does not link dictionaries. What it does is in line cities[states['Michigan']] it first evaluates states['Michigan'] to the value of 'Michigan' in states dictionary (which is 'MI'). After that expression looks like cities['MI']. And then it evaluates it to value of 'MI' from cities dictionary (which is 'Detroit').

Answered By: Yevhen Kuzmovych

It resolves not quite backwards, but in order of innermost expression -> outermost expression.

So, for cities[states['Michigan']], it will

  1. Looks at cities
  2. Recognize it needs to resolve states['Michigan']
  3. Look at states
  4. Find states['Michigan']
  5. Return value of states['Michigan'] to cities
  6. Now it can resolve cities[states['Michigan']]
Answered By: Will

This is how the Python interpreter evaluates the expressions for a dictionary lookup.

  1. In following expression it looks for the value of given key 'Michigan' in the dict states:

    states['Michigan']

    The resulting value, after evaluating this expression, is "MI".

  2. Then it takes this evaluated value and uses it to lookup inside the cities dict. Knowing the first expression returned "MI" an equivalent lookup expression would be:

    cities['MI']

Answered By: Le Ray
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.