Home > Software design >  Python3 Pop Nested Json Key Give a String Path
Python3 Pop Nested Json Key Give a String Path

Time:08-10

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?

CodePudding user response:

Maybe something like this:

def get(d, lst):
    for i in range(len(lst) - 1):
        d = d[lst[i]]
    d.pop(lst[-1])
    return data


print(get(data, lst))

Output:

{'IP': {'key2': 'val2'}}

CodePudding user response:

Check this out!

data = {'IP': {'key1': 'val1', 'key2': 'val2'}}
lst = ['IP', 'key1']

for i in range(len(lst) - 1):
    d = data[lst[i]]
d.pop(lst[-1])

print(data)

Output :

{'IP': {'key2': 'val2'}}

CodePudding user response:

data = {'IP': {'key1': 'val1', 'key2': 'val2'}}
lst = ['IP', 'key1']

current_level = data
for key in lst[:-1]:
    current_level = current_level[key]
current_level.pop(lst[-1])
  • Related