Python 3.x 遍历字典中的键

Python 3.x 遍历字典中的键,python-3.x,dictionary,casting,Python 3.x,Dictionary,Casting,输出: nums={'1':'one', '2':'two', '3':'three', '4':'four', '5':'five'} nums['6']='six' for i in range(1,7): print(nums[str[i]]) 我找到了在键为int类型时执行此操作的其他方法,但我仍然好奇它为什么不起作用。您需要调用str类型: TypeError: 'type' object is not subscriptable 您试图用str[i](方括号)索引str

输出:

nums={'1':'one',
'2':'two',
'3':'three',
'4':'four',
'5':'five'}

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

我找到了在键为int类型时执行此操作的其他方法,但我仍然好奇它为什么不起作用。

您需要调用
str
类型:

TypeError: 'type' object is not subscriptable
您试图用
str[i]
(方括号)索引
str

print(nums[str(i)])