简体   繁体   English

尝试访问字典中的键时引发 KeyError - 键存在

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

I know a lot of similar questions like this have been asked, but none of them solved my problem.我知道有人问过很多类似的问题,但没有一个能解决我的问题。 i want to access the parts of this nested dictionary that have the 'leaf':'leaf' key-value pair:我想访问这个嵌套字典中具有 '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'}}

here is my code:这是我的代码:

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)

this yields a key error:这会产生一个关键错误:

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'

I tried it with other elements of the dictionary, like the parent_id key, and that worked.我尝试了字典的其他元素,比如 parent_id 键,并且成功了。 I thought it could be something to do with the uniqueness of the entry, but it cant be that, because the parent_id is also not unique.我认为这可能与条目的唯一性有关,但事实并非如此,因为 parent_id 也不是唯一的。 Maybe something to do with the fact the value is a string?也许与值是字符串的事实有关? I couldnt find much on this either though.不过,我也找不到太多。 I then tried editing the key-value pair by writing 'leaf': 1 for the leaf and 'leaf': 0 for not_leaf - but i still got the same error.然后我尝试通过为叶子编写'leaf': 1和为 not_leaf 编写'leaf': 0来编辑键值对 - 但我仍然遇到相同的错误。 So I guess its a problem with the key part, not the value part.所以我猜这是关键部分的问题,而不是价值部分。

I appreicate any help, thank you!我很感激任何帮助,谢谢!

key error is raised when a key is not in the dictionary.当键不在字典中时会引发键错误。 Here 'leaf' is not in tree[0], so it raises this error.这里 'leaf' 不在树 [0] 中,因此会引发此错误。 You can put a check like this你可以这样检查

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

You can also use get()您也可以使用 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