【问题标题】:Using integers to access a key, value pairs in a dictionary?使用整数访问字典中的键值对?
【发布时间】: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


【解决方案1】:

在尝试访问字典之前将数字转换为字符串:

for i in range(1,6):
    if self.compare(image1, example[str(i)]) > 0.8:
        return True

或者使用整数键而不是字符串作为数字键创建字典。

【讨论】:

    【解决方案2】:

    您只需要将整数转换为字符串以匹配您的字典键格式。

    如果您不介意在没有一个比较超过您的阈值 0.8 时返回 False,您可以这样做:

    return any(self.compare(image1, example[str(i)]) > 0.8 for i in range(1, 6))
    

    【讨论】:

      猜你喜欢
      • 2012-03-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多