2
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)

Nir Alfasi
  • 53,191
  • 11
  • 86
  • 129
Mihir
  • 73
  • 1
  • 10
  • 1
    Possible duplicate of [Accessing elements of python dictionary](https://stackoverflow.com/questions/5404665/accessing-elements-of-python-dictionary) – Nir Alfasi Jun 06 '17 at 04:35

3 Answers3

4

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']
Miriam Farber
  • 18,986
  • 14
  • 61
  • 76
0

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"

mathers25
  • 133
  • 1
  • 2
  • 9
0

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' }

Noved
  • 68
  • 1
  • 6
  • 1
    Welcome to Stack Overflow! Please provide an example of code that would work in this situation if possible. – codeMonkey Dec 29 '17 at 19:31