定义映射时出现 Python 语法错误 [英] Python syntax error when defining a mapping
本文介绍了定义映射时出现 Python 语法错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在 Linux 机器上使用 python 2.7.4.我的指南是艰难地学习 Python"这本书,我正在进行第 39 次练习,这是我的代码:
I am using python 2.7.4 on a Linux machine. My guide is the book "Learn Python the hard way" and I am at 39th exercise and here's my code:
# 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
我尝试复制粘贴确切的代码,但仍然收到相同的错误.冒号是如何导致错误的?任何帮助将不胜感激.
I have tried copy pasting the exact code but still I receive the same error. How is that colon responsible for the error? Any help will be much appreciated.
推荐答案
您使用错误的语法来定义字典.您需要使用 {..}
(花括号),而不是 [..]
(方括号,用于列表):
You are using the wrong syntax to define a dictionary. You need to use {..}
(curly braces), not [..]
(square brackets, used for lists):
# 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',
}
键值对之间的逗号也是必须的.
The commas between key-value pairs are mandatory too.
这篇关于定义映射时出现 Python 语法错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文