簡體   English   中英

嘗試訪問字典中的鍵時引發 KeyError - 鍵存在

[英]KeyError raised when trying to access a key in a dictionary - the key exists

我知道有人問過很多類似的問題,但沒有一個能解決我的問題。 我想訪問這個嵌套字典中具有 'leaf':'leaf' 鍵值對的部分:

tree={0: {'coords': [0],
  'bounds': (0, 84),
  'thres': 3e-08,
  'id': 0,
  'depol532_mean': 0.11638256238679075},
 1: {'coords': [0, 0],
  'bounds': (0, 54),
  'thres': 3e-08,
  'parent_id': 0,
  'id': 1,
  'depol532_mean': 0.13970860650679306,
  'leaf': 'not_leaf'},
 3: {'coords': [0, 0, 0],
  'bounds': (0, 22),
  'thres': 9.833542446299045e-07,
  'parent_id': 1,
  'id': 3,
  'depol532_mean': 0.15483549951519165,
  'leaf': 'leaf'},
   4: {'coords': [0, 0, 1],
  'bounds': (22, 54),
  'thres': 9.833542446299045e-07,
  'parent_id': 1,
  'id': 4,
  'depol532_mean': 0.1296008883894188,
  'leaf': 'leaf'}}

這是我的代碼:

for node in tree:
    #if tree[node]['parent_id']==1: this works - why doesnt the leaf thing?
    if tree[node]['leaf']=='leaf':
        print('its true!', node)
    else:
        print('nope!', node)

這會產生一個關鍵錯誤:

KeyError                                  Traceback (most recent call last)
<ipython-input-14-eae55d0dcfe0> in <module>
      2 for node in tree:
      3     #if tree[node]['parent_id']==1: this works - why doesnt the leaf thing?
----> 4     if tree[node]['leaf']=='leaf':
      5         print('nope!', node)
      6     else:

KeyError: 'leaf'

我嘗試了字典的其他元素,比如 parent_id 鍵,並且成功了。 我認為這可能與條目的唯一性有關,但事實並非如此,因為 parent_id 也不是唯一的。 也許與值是字符串的事實有關? 不過,我也找不到太多。 然后我嘗試通過為葉子編寫'leaf': 1和為 not_leaf 編寫'leaf': 0來編輯鍵值對 - 但我仍然遇到相同的錯誤。 所以我猜這是關鍵部分的問題,而不是價值部分。

我很感激任何幫助,謝謝!

當鍵不在字典中時會引發鍵錯誤。 這里 'leaf' 不在樹 [0] 中,因此會引發此錯誤。 你可以這樣檢查

if 'leaf' in tree[node] and tree[node]['leaf']=='leaf':
    print('its true!', node)
else:
    print('nope!', node)

您也可以使用 get()

if tree[node].get('leaf') == 'leaf':
    print('its true!', node)

暫無
暫無

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

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