简体   繁体   中英

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:

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. 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. 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. 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. 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()

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM