简体   繁体   中英

Why does this dict give me a syntax error?

#create a mapping of state to abbreviation
states = [
    'Oregon': 'OR',
    'Florida': 'FL',
    'California': 'CA',
    'New York': 'NY',
    'Michigan': 'MI',
]

I'm working through Learn Python the Hard Way, and this lesson has me stumped. I've looked everywhere, but I can't figure out why it's giving me this error :

oldlink:my-python HarveyMark$ python ex39.py
  File "ex39.py", line 3
    'Oregon': 'OR',
            ^
SyntaxError: invalid syntax

When you use [ it indicates that you are defining a list , not a dict .

For a dict use { and } . Example -

states = {
    'Oregon': 'OR',
    'Florida': 'FL',
    'California': 'CA',
    'New York': 'NY',
    'Michigan': 'MI',
}

As explained in the comments, dictionaries use curly brackets {} .

The correct code is:

states = {
    'Oregon': 'OR',
    'Florida': 'FL',
    'California': 'CA',
    'New York': 'NY',
    'Michigan': 'MI',
}

Just to clarify your error, you used square brackets (which are used for lists ). The error states that it was expecting a comma to separate the elements rather than a colon.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM