2

I have this dictionary,

states = {
    'CT': 'Connecticut',
    'CA': 'California',
    'NY': 'New York',
    'NJ': 'New Jersey'
    }

and code here..

state2 = {state: abbrev for abbrev, state in states.items()}

I'm trying to understand what and how this abbrev for abbrev works. Also it's not clear to me what state: is exactly. I get the second part (state in states.items()). The output of this gives

{'Connecticut': 'CT', 'California': 'CA', 'New York': 'NY', 'New Jersey': 'NJ'}

but I'm not sure how this is working.. Thank you in advance.

piRSquared
  • 285,575
  • 57
  • 475
  • 624
abkf12
  • 219
  • 3
  • 14
  • Does this answer your question? [Create a dictionary with list comprehension](https://stackoverflow.com/questions/1747817/create-a-dictionary-with-list-comprehension) – Sayse Jan 09 '20 at 20:15

2 Answers2

5

What is happening here is called a dictionary comprehension, and it's pretty easy to read once you've seen them enough.

state2 = {state: abbrev for abbrev, state in states.items()}

If you take a look at state: abbrev you can immediately tell this is a regular object assigning syntax. You're assigning the value of abbrev, to a key of state. But what is state, and abbrev?

You just have to look at the next statement, for abbrev, state in states.items()

Here there's a for loop, where abbrev is the key, and state is the item, since states.items() returns us a key and value pair.

So it looks like a dictionary comprehension is creating an object for us, by looping through an object and assigning the keys and values as it loops over.

alex067
  • 3,159
  • 1
  • 11
  • 17
  • For a smidgen of added context, this is the same as `dict(map(reversed, states.items()))` and related to [this Q&A](https://stackoverflow.com/q/483666/2336654) – piRSquared Jan 09 '20 at 20:44
1

Dictionary comprehensions are similar to list comprehensions. states.items() is a generator that will return the key and value for each item in the original dictionary. So if you were to declare an empty dictionary, loop through the items, and then flip the key and value, you would have a new dictioary that is a flipped version of the original.

state2 = {}
for abbrev, state in states.items():
    state2[state] = abbrev

To convert from a loop structure

Flip the order of the lines

state2 = {}
    state2[state] = abbrev
for abbrev, state in states.items():

Extend the bracket to envelop everything

state2 = {
    state2[state] = abbrev
for abbrev, state in states.items():
}

fix the assignment since state2 isn't assigned

state2 = {
    state: abbrev
for abbrev, state in states.items():
}

Drop the original :

state2 = {
    state: abbrev
for abbrev, state in states.items()
}

Tidy up the lines

state2 = {state: abbrev for abbrev, state in states.items()}

Using the comprehension sytax is generally faster and preferred.

Cohan
  • 4,384
  • 2
  • 22
  • 40