Reputation: 73
states = [
'Oregon': 'OR',
'Florida': 'FL',
'California': 'CA',
'New York': 'NY',
'Michigan': 'MI'
]
print states.Oregon
Why is this code showing syntax error in line 2? Running on python 2.7.12 (default on ubuntu)
Upvotes: 2
Views: 770
Reputation: 68
The issue is actually in the book. I would be happy to provide a screenshot if necessary. The book uses incorrect syntax in the lesson itself, and it is not the fault of the person who posted this question or anyone else stumped by this. Yes we should be able to utilize critical thinking and, from a previous example in the same lesson, apply the correct syntax...but this book is meant for beginners who may not make that connection right away.
ex39.py lists the syntax as states = [ 'Oregon': 'OR' .... .... ]
The correct syntax, as was already explained, would be states = { 'Oregon': 'OR' }
Upvotes: 0
Reputation: 19634
First of all, for a dictionary in python you should use the brackets {} and not []. In addition, if you want to access an element of a dictionary in python, you should write:
states = { 'Oregon': 'OR', 'Florida': 'FL', 'California': 'CA', 'New York': 'NY', 'Michigan': 'MI' }
print states['Oregon']
Upvotes: 4
Reputation: 125
You're mixing up the syntax for a list and a dictionary in python.For representing keys and values we use a dictionary and we'll be using curly braces"{}" instead of "[]". Eg. Oregon represent a key,therefore to find the value for the corresponding key just type -> print states['Oregon'].This will print out the corresponding value i.e "OR"
Upvotes: 0