我是一名蟒蛇初学者。在练习了学习Python的艰难之路后,我尝试用字典写我的家乡城市。
以下是我写的内容:
states = {
'Orangon': 'OR',
'Florida': 'FL',
'California': 'CA',
'New York': 'NY',
'Michigan': 'MI',
}
for state, abbrev in states.items():
print "%s is abbreviated %s" % (state, abbrev)
print states.get('Florida')
print states.get('California')
cities = {
'New Taipei': 'NTP',
'Taipei': 'TP',
'Kaohsiung': 'KHU',
'Taichung': 'TAC',
'Taoyuan': 'TYN',
'Tainan': 'TNA',
'Hsinchu': 'HSC',
'Keelung': 'KLG',
'Chiayi': 'CYI',
'Changhua': 'CHA',
'Pingtung': 'PTG',
'Zhubei': 'ZBI',
'Yuanlin': 'Yln',
'Douliu': 'Dlu',
'Taitung': 'TAT',
'Hualien': 'HUl',
'Toufen': 'TFE',
'Yilan': 'Yln',
'Miaoli': 'Mli',
'Magong': 'Mgn',
}
for cities, abbrev in cities.items():
print "%s is %s" % (cities, abbrev)
print cities.get('Magong')
上一段代码中有错误:
追踪(最近一次通话): 文件" ex39.2.py",第27行,in 打印cities.get(' Magong') AttributeError:' str'对象没有属性' get'
我不明白为什么print states.get('California')
没有错误,但print cities.get('Magong')
答案 0 :(得分:3)
在for循环中,您将字符串分配给变量cities
:
for cities, abbrev in cities.items():
print "%s is %s" % (cities, abbrev)
因此,在for循环之后,cities
不再是一个字典,而是一个字符串。
解决方案:在循环中使用不同的变量:
for city, abbrev in cities.items():
print "%s is %s" % (city, abbrev)