使用整数访问字典中的键值对?
Using integers to access a key, value pairs in a dictionary?
问题:如何使用整数作为字典的键?
说明:
我有一本字典
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
在控制台 window 中,如果我尝试使用 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
在尝试访问字典之前将数字转换为字符串:
for i in range(1,6):
if self.compare(image1, example[str(i)]) > 0.8:
return True
或者使用整数键而不是字符串作为数字键来创建字典。
您只需将整数转换为字符串以匹配您的字典键格式。
如果您不介意在 none 比较超过阈值 0.8 时返回 False,您可以这样做:
return any(self.compare(image1, example[str(i)]) > 0.8 for i in range(1, 6))
问题:如何使用整数作为字典的键?
说明: 我有一本字典
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
在控制台 window 中,如果我尝试使用 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
在尝试访问字典之前将数字转换为字符串:
for i in range(1,6):
if self.compare(image1, example[str(i)]) > 0.8:
return True
或者使用整数键而不是字符串作为数字键来创建字典。
您只需将整数转换为字符串以匹配您的字典键格式。
如果您不介意在 none 比较超过阈值 0.8 时返回 False,您可以这样做:
return any(self.compare(image1, example[str(i)]) > 0.8 for i in range(1, 6))