“str”对象没有属性“get”学习Python的方法很难EX39

2024-04-25 22:05:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我是Python初学者。在苦练了《学Python》的ex39后,我试着用字典来写我的家乡城市。在

以下是我写的:

    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 打印城市。获取(“马公”) AttributeError:“str”对象没有属性“get”

我不明白为什么print states.get('California')中没有错误,print cities.get('Magong')中却有错误


Tags: innewforgetis错误itemsstate
1条回答
网友
1楼 · 发布于 2024-04-25 22:05:47

在for循环中,为变量cities分配一个字符串:

for cities, abbrev in cities.items():
    print "%s is %s" % (cities, abbrev)

因此,在for循环之后,cities不再是dict,而是一个字符串。在

解决方案:在循环中使用其他变量:

^{pr2}$

相关问题 更多 >