apparently, there is no built-in dict method (let’s call it .nestkey
) for dynamic key addressing in multi-nested dict structures. this can be demanding when dealing with complex dict structures,
e.g., dic_1.nestkey(list_of_keys_A) = value
instead of manually doing dic_1["key_1"]["subkey_2"]["subsubkey_3"].. = value
.
this is not to be confused with level-1 assignment: dic_1["key_1"] = value_1, dic_2["key_2"] = value_2, ..
.
i know it’s generally good practice to avoid nested structures, but when necessary, dynamic addressing is powerful:
list_values = [1, 2, 3]; ii = -1
for list_nestedkeys_i in [list_nestedkeys_A, list_nestedkeys_B, list_nestedkeys_C]:
ii += 1; dic.nestkey(list_nestedkeys_i) = list_values[ii]
# endfor
for this purpose, i suggest implementing .nestkey
as a built-in dict
method. here’s how it could be expressed in method format:
def nestkey(self, keys, value):
d = self # the nested dict
for key in keys[:-1]: # traverse to the second last key
if key not in d:
d[key] = {} # create a nested dict if key doesn't exist
# endif
d = d[key] # move deeper into the dict
# endfor
d[keys[-1]] = value # set the value for the final key
# enddef
1