2017-06-29 40 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