繁体   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