python - 尝试迭代字典时出现类型错误: 'int' 不可迭代

标签 python loops dictionary iteration typeerror

我对 python 有点陌生,我一直在尝试找到一种方法来迭代字典,其键如下:

r_alpha: {1: 'a', 2: 'b', 3: 'c', 4: 'd', 5: 'e', 6: 'f', 7: 'g', 8: 'h', 9: 'i', 10: 'j', 11: 'k', 12: 'l', 13: 'm', 14: 'n', 15: 'o', 16: 'p', 17: 'q', 18: 'r', 19: 's', 20: 't', 21: 'u', 22: 'v', 23: 'w', 24: 'x', 25: 'y', 26: 'z'}

让我们假设以下情况: 我有一个列表,我想查找列表的值是否在字典键中并打印该键的值,但会发生这种情况:

th = [1,2,3]
for item in th:
for keys, values in r_alpha.items():
        if item in keys:
            print(values)

我收到以下错误,指向第 4 行(如果键中有项目:) 类型错误:“int”类型的参数不可迭代

如果我将该列表更改为字符串值,我实际上会得到像这样的字符串值的键:

th = ['a','b','c']
for item in th:
for keys, values in r_alpha.items():
        if item in values:
            print(keys)

打印:1 2 3

有人可以帮助我并告诉我我做错了什么吗?或者如何迭代字典的 int 键以便返回值。

最佳答案

错误的原因是因为您在循环中迭代键,并且在每次迭代时使用 in 运算符将键与其他值进行比较,该运算符用于可迭代的成员资格测试。由于您的键是整数(不是可迭代的),因此这显然不起作用。

<小时/>

当字典支持恒定时间查找时,无需迭代字典的键。

for item in th:
    if item in r_alpha:
        print(r_alpha[item])
a
b
c

或者,您可以使用 dict.get 删除 if 条件。

for item in th:
    print(r_alpha.get(item))
a
b
c

关于python - 尝试迭代字典时出现类型错误: 'int' 不可迭代,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45992968/

相关文章:

swift - 如何检查字典中的值?

python - Django 多个数据库的简单分步指南请

Python 复制带条件的子列表

javascript - 为什么我的 while 循环没有完全迭代?

php - 确定 foreach 循环在其最终迭代中的最简单方法

Python - 确定井字游戏的赢家

python - 组中最后一项的虚拟变量

python - Pony ORM 报告记录 "was updated outside of current transaction"而没有其他事务

python - 访问值列表中的特定值

Python:从value中获取对应的key