Home > OS >  How do I convert a flat JSON key to a dictionary path?
How do I convert a flat JSON key to a dictionary path?

Time:11-22

Let's say I have this dictionary:

temp = {"a": {"b": {"c": 123} } } 

And I have the following flat JSON key and new value:

flat = "a.b.c"
new_val = 456

I'd like to change the nested dict value with the new one. How do I transform the "a.b.c" to temp["a"]["b"]["c"]?

Note that I don't know the amount of layers in the JSON key, it can be "a.b.c.d.f" and it could be just "a".

CodePudding user response:

You need to iterate the different keys (execpt the last one) to reach the final dict, then update the value

def update_dict_dot(values, key: str, val):
    keys = key.split(".")
    x = values
    for key in keys[:-1]:
        x = x[key]
    x[keys[-1]] = val
temp = {"a": {"b": {"c": 123}}}
print(temp)  # {'a': {'b': {'c': 123}}}
update_dict_dot(temp, "a.b.c", 456)
print(temp)  # {'a': {'b': {'c': 456}}}

CodePudding user response:

Like @rdas mentioned here is the code to do that

temp = {"a": {"b": {"c":{"d": 123} } } }
flat = "a.b.c.d"
new_val = 456
split_val = flat.split('.')
trav_data = temp
for keys in split_val:
    trav_data = trav_data[keys]
print(trav_data)

output

123
  • Related