定义映射时出现Python语法错误

时间:2014-06-17 11:39:12

标签: python syntax

我在Linux机器上使用python 2.7.4。我的指南是“艰难学习Python”这本书,我正在进行第39次练习,这是我的代码:

# states and their abberavation
states = [
'Bihar' : 'BIH'
'Jharkhand' : 'JK'
'Bengal' : 'BEN'
'Tamilnadu' : 'TN'
'Haryana' : 'HY'
'Kerla' : 'KER'
]

# states with their cities
cities = [
'BIH' : 'Patna'
'JK' : 'Ranchi'
'BEN' : 'Kolkatta'
]

# add some more cities
cities['CHN'] = 'Chennai'
cities['BWN'] = 'Bhiwani'

 #print out some cities
print '-' * 10
print "TN State has:", cities['CHN']
print "HY State has:", cities['BWN']

# print some states
print '-' * 10
print "Kerla's abbreviation is :", states['Kerla']
print "Jharkhand's abbreviation is:", states['Jharkhand']

# do it by using the state then cities dict
print '-' * 10
print "Bihar has:", cities[states['Bihar']]
print "Bengal has", cities[states['Bengal']]

# print every state abbreviation
print '-' * 10
for state, abbrev in states.items():
    print "%s is abbreviated %s" % (state, abbrev)

# print every city in state
print '-' * 10
for abbrev, city in cities.items():
    print "%s has the city %s" % (abbrev, city)

# now do both at the same time
print '-' * 10
for state, abbrev in states.items():
    print "%s state is abbreviated %s and has city %s" % (state, abbrev, cities[abbrev])

print '-' * 10
#safely get an abbreviation by state that might not be there
state = states.get('Maharashtra', None)

if not state:
    print "Sorry, no Maharashtra."

#get a city with a default value
city = cities.get('MH' 'Does Not Exist')
print "The city for the state 'MH' is: %s" % city

我得到的错误很简单,

File "ex39.py", line 3
    'Bihar' : 'BIH'
            ^
SyntaxError: invalid syntax

我试过复制粘贴确切的代码但仍然收到相同的错误。那个冒号怎么对错误负责?任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:2)

您使用错误的语法来定义字典。您需要使用{..}(花括号),而不是[..](方括号,用于列表):

# states and their abbreviation
states = {
    'Bihar': 'BIH',
    'Jharkhand': 'JK',
    'Bengal': 'BEN',
    'Tamilnadu': 'TN',
    'Haryana': 'HY',
    'Kerla': 'KER',
}

# states with their cities
cities = {
    'BIH': 'Patna',
    'JK': 'Ranchi',
    'BEN': 'Kolkatta',
}

键值对之间的逗号也是强制性的。

答案 1 :(得分:0)

用于定义状态的数据类型,城市应该是字典。

states = {
'Bihar' : 'BIH',
'Jharkhand' : 'JK',
'Bengal' : 'BEN',
'Tamilnadu' : 'TN',
'Haryana' : 'HY',
'Kerla' : 'KER'
}

您应该为cities更改相同内容 请点击此链接了解字典。python doc