Search code examples
pythondictionarydictionary-comprehensioniterable-unpacking

Python dictionary syntax, having a for condition


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.


Solution

  • 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.