【问题标题】:Iterating through keys in dictionaries遍历字典中的键
【发布时间】:2014-05-15 10:52:01
【问题描述】:
nums={'1':'one',
'2':'two',
'3':'three',
'4':'four',
'5':'five'}

nums['6']='six'
for i in range(1,7):
    print(nums[str[i]])

输出:

TypeError: 'type' object is not subscriptable

当键是 int 类型时,我发现了替代方法,但我仍然很好奇为什么它不起作用。

【问题讨论】:

    标签: python-3.x dictionary casting


    【解决方案1】:

    您需要调用str类型:

    print(nums[str(i)])
    

    您试图用str[i](方括号)索引str

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-11-23
      • 2022-01-14
      • 1970-01-01
      • 1970-01-01
      • 2015-04-16
      • 1970-01-01
      • 1970-01-01
      • 2013-05-18
      相关资源
      最近更新 更多