I apologize in advance if there's already a question answering this problem but I didn't find any that helped. Essentially, I have a nested dictionary with n-levels, i.e.,
nested_dict = {
"lvl_1a": {
"lvl_2a_1": {
"lvl_3a_1": 1,
"lvl_3b_1": 2,
...,
},
"lvl_2b_1": {
"lvl_3a_2": 5,
"lvl_3b_2": 6,
...,
},
"lvl_1b": {
"lvl_2a_2": {
"lvl_3a_3": 1,
"lvl_3b_3": 2,
...,
}
}
}
and a key I want to remove, say that is, "lvl_3a_3". This is what I have so far
def remove_a_key(d, remove_key):
if isinstance(d, dict) and d:
for key in list(d.keys()):
if key == remove_key:
del d[key]
return d
elif not d[key]:
del d[key]
return remove_a_key(d, remove_key)
else:
return remove_a_key(d[key], remove_key)
modified_dictionary = remove_a_key(nested_dictionary, "lvl_3a_3")
with the help of another
StackOverflow question.
But once it finds the key
to remove, and return d
is expected, it continues to the else
-statement instead of completely exiting out of the function. In fact, it runs the else
-statement twice before completely exiting out. I'm not sure what's going on except that somehow I'm referencing the function and thus it's not returning properly.