初学Python 字典调用出错

这是出错的代码片段,错误类型是:string indices must be integers, not str

 for state, abbrev in states.items():
    print "%s state is abbreviation %s and has city %s" % (
        state, abbrev, cities[abbrev])

额,我不太明白,字典的key本身不要求是数字,为什么这里会出错。

下面是完整的代码

# -*- coding: utf-8 -*-
# creat a mapping of state to abbreviation
states = {
    'Oregon':'OR',
    'Florida':'FL',
    'California':'CA',
    'New York':'NY',
    'Michigan':'MI'
}

#creat a basic set of set and some cities in them
cities = {
    'CA':'San Francisco',
    'MI':'Detroit',
    'FL':'Jacksonville'
}

# add some cities
cities['NY'] = 'New York'
cities['OR'] = 'Portland'

# print some cities
print '-' * 10
print "CA has %s:" % cities['CA']
print "NY has %s:" % cities['NY']

# print some states
print '-' * 10
print "Oregon is:", states['Oregon']
print "California is:", states['California']

#print some states and its cities
print '-' * 10
print "Michigan has:", cities[states['Michigan']]
print "California has:", cities[states['California']]

# print all states and its abbreviation
print '-' * 10
for state, abbrev in states.items():
    print '%s has an abbreviation: %s'% (state, abbrev)

# print all abbreviation and its cities
print '-' * 10
for abbrev, cities in cities.items():
    print '%s has %s.' % (abbrev, cities)

# print now do both at the same time
print '-' * 10
for state, abbrev in states.items():
    print "%s state is abbreviation %s and has city %s" % (
        state, abbrev, cities[abbrev]) # 出错代码行

print '-' * 10
state = states.get('Texas', None)

if not state:
    print "Sorry, no Texas."

city = cities.get('TX', 'Does Not Exist')
print "The city for the state 'TX' is %s." % city

for abbrev, cities in cities.items():
print '%s has %s.' % (abbrev, cities)

这个for 循环执行后,cities 就变成字符串了。
改一下for 里面这个变量名就ok了