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

I am learning Python from Learning Python The Hard Way. In example 39 of the book, I typed the same code as shown above for creating a dictionary, even copied and pasted it, but I m getting an error E0001:invalid syntax (<string>, line 3) and it is pointing at :. What went wrong?

2 Answers 2

3

Square brackets ([]) are used for list literals. In this case, you're supposed to be making a dict literal (the : is used to separate the key on the left of the colon from the value on the right), which is delimited by curly braces ({}).

Sign up to request clarification or add additional context in comments.

5 Comments

I changed the ( [ ] ) to ( { } ), it still shows the same error
@AnkurSatpute: You either forgot to save after editing, or saved to the wrong file, or made some other mistake not shown in your question. If your code in the question replaced [ with { and ] with } it would be syntactically valid; I can't guess at what other mistakes you might have made.
@AnkurSatpute: When you use brackets, the : is illegal, when you use braces, it's legal. SyntaxErrors are raised at the point where the parser gives up, and until you reach the colon, nothing was wrong.
This is the snapshot of the code given in the book. drive.google.com/file/d/1RXmc_5RPBp-4EVGMQHr7xkBvWwpP20aK/…
@AnkurSatpute: Your copy is wrong. Someone else excerpted the code correctly here, as well as here; I can't explain why yours is wrong, and a two year old excerpt is correct.
2

You want to use curly braces for dictionaries

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

3 Comments

I changed it to { }, but it still shows the same error pointing at ' : '
Copy and paste the code into your python interpreter, and it should work. Check your file for hidden characters or tabs.
This is the snapshot of the code in the book drive.google.com/file/d/1RXmc_5RPBp-4EVGMQHr7xkBvWwpP20aK/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.