Coastharukun 2016-08-18 08:08 采纳率: 0%
浏览 1121

初学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

  • 写回答

1条回答 默认 最新

  • Leon.SHAO 2016-08-18 08:16
    关注

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

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

    评论

报告相同问题?

悬赏问题

  • ¥15 三菱伺服电机按启动按钮有使能但不动作
  • ¥20 为什么我写出来的绘图程序是这样的,有没有lao哥改一下
  • ¥15 js,页面2返回页面1时定位进入的设备
  • ¥200 关于#c++#的问题,请各位专家解答!网站的邀请码
  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号