簡體   English   中英

使用整數訪問鍵,字典中的值對?

[英]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

在控制台窗口中,如果我嘗試使用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

或使用整數鍵而不是數字鍵的字符串創建字典。

您只需要將整數轉換為字符串即可匹配您的字典鍵格式。

如果您不介意如果沒有一個比較值超過您的閾值0.8,則返回False,則可以執行以下操作:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM