2017-06-29 41 views
0

我是一名python初学者。在学习Python的困难之路之前,我试着用字典来写我的家乡城市。'str'对象没有属性'get' - 学习Python The Hard Way 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行,在 打印cities.get(“马公”) AttributeError的:“海峡”对象有没有属性“得到”

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

回答

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) 
+0

我知道了。谢谢 :) – Paige