【发布时间】:2017-01-21 15:52:13
【问题描述】:
问题:如何使用整数作为字典的键?
说明: 我有一本字典
example = {}
我用键、值对填充它
A: something
B: something
C: something
1: something
2: something
3: something
4: something
5: something
6: something
现在我需要遍历这本词典的 1 - 6 个条目
for i in range(1,6):
if self.compare(image1, example[i])>0.8:
return True
现在由于原始字典中的键是字符串,而这里的 'i' 是整数格式,我得到了错误:
if self.compare(image1, example[i])>0.8:
KeyError: 0
在控制台窗口中,如果我尝试使用 example["1"] 访问字典键,它会向我显示其内容,但当我尝试将其显示为 example[1] 时,它会向我显示:
print example[1]
Traceback (most recent call last):
File "pydevd_comm.py", line 1080, in do_it
result = pydevd_vars.evaluate_expression(self.thread_id, self.frame_id, self.expression, self.doExec)
File "pydevd_vars.py", line 352, in evaluate_expression
Exec(expression, updated_globals, frame.f_locals)
File "pydevd_exec.py", line 3, in Exec
exec exp in global_vars, local_vars
File "<string>", line 1, in <module>
KeyError: 1
【问题讨论】:
-
例子[str(i)]
-
@Alexander 因为你是第一个进入这个的。请将此添加为评论,以便我可以将其标记为答案
标签: python loops dictionary key key-value