[Python] Python3 Pop Nested Json Key Give a String Path

Discussão em 'Python' iniciado por Stack, Fevereiro 11, 2025.

  1. Stack

    Stack Membro Participativo

    Use Case

    I need to Pop() a nested JSON key based on a variable length string that is passed to my script.

    Example

    Given the dictionary {'IP': {'key1': 'val1', 'key2': 'val2'}} how can Pop() the key1 value out of the dictionary if my script is passed the path as IP.key1

    Note this would need to work given any number of keys.

    So far I have found this code snippet on Stack which works in finding the key, but I can't get this to actually remove the key:

    data = {'IP': {'key1': 'val1', 'key2': 'val2'}}
    lst = ['IP', 'key1'] # Convert the string of keys to an array

    def get(d,l):
    if len(l)==1: return d[l[0]]
    return get(d[l[0]],l[1:])

    print(get(data, lst))


    Also, I am working in a restricted environment, so using any niche libs is not an option.

    I feel like there is probably an easy way to adapt this to pop the full path, but the recursion is hurting my head. Any thoughts?

    EDIT

    The answer from Filip Müller seems to be working for me. But he didn't provide much context so I am updating this to demonstrate a more complex data set and the function I used based on Filip's answer

    data = {'IP': {'key1': {'key3': {'key4': 'val4', 'key5': 'val5'}}, 'key2': 'val2'}}
    lst = ['IP', 'key1', 'key3', 'key4']


    def popKey(d, l):
    current_level = d
    for key in l[:-1]:
    print(key)
    current_level = current_level[key]
    print(current_level)
    current_level.pop(l[-1])
    return d


    print(popKey(data, lst))

    Continue reading...

Compartilhe esta Página