Alexander Zhak Alexander Zhak - 4 months ago 19
Python Question

How to dive into stacked dict gracefully

Let's say I have a dict like

{
"key_a": "value",
"key_b": {
"key_b_a": "value",
"key_b_b": {
"key_b_b_a": "value"
}
}
}


What I want is to create a method to delete the given key or change its value.

def del_key(key):
my_dict = <dictionary described above>
keys = key.split(':')
if len(keys) == 1:
del my_dict[keys[0]]
elif len(keys) == 2:
del my_dict[keys[0]][keys[1]]
elif len(keys) == 3:
del my_dict[keys[0]][keys[1]][keys[2]]
. . .

del_key('key_b:key_b_b:key_b_b_a')
del_key('key_b:key_b_b')
del_key('key_a')


How can I do this gracefully?

Answer

It assumes your input is valid key,otherwise you have to check.

data = {
    "key_a": "value",
    "key_b": {
        "key_b_a": "value",
        "key_b_b": {
            "key_b_b_a": "value"
        }
    }
}

def del_key(key):
    key = key.split(':')
    temp = data
    for i in key[:-1]:
        temp = temp[i]
    del temp[key[-1]]
    return data

print del_key('key_b:key_b_b:key_b_b_a')
print del_key('key_b:key_b_b')
print del_key('key_a')

output:
{'key_a': 'value', 'key_b': {'key_b_a': 'value', 'key_b_b': {}}}
{'key_a': 'value', 'key_b': {'key_b_a': 'value'}}
{'key_b': {'key_b_a': 'value'}}
Comments