定义映射时Python语法错误

-4 投票
2 回答
1032 浏览
提问于 2025-04-18 10:04

我在一台运行Linux的机器上使用Python 2.7.4。我正在参考一本书《Learn Python the Hard Way》,现在到了第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

你用来定义州和城市的数据类型应该是字典。

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

你也应该把cities改成一样的格式。
请点击这个链接了解字典的用法。python文档

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

在键值对之间的逗号也是必须的。

撰写回答