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

Discussão em 'Python' iniciado por Stack, Junho 12, 2025.

  1. Stack

    Stack Membro Participativo

    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 can't be that, because the parent_id is also not unique.

    Maybe it's something to do with the fact the value is a string? I couldn't 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 it's a problem with the key part, not the value part.

    Continue reading...

Compartilhe esta Página