Dict built-in get/set methods for nested keys

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 implement a set/get couple of built-in dict methods, setnest and getnest respectively,

def setnest(self, lis_nestkey, value): 
    d = self
    for key in lis_nestkey[:-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[lis_nestkey[-1]] = value  # set the value for the final key`
#enddef setnest


def getnest(self, lis_nestkey): 
    d = self
    for key in lis_nestkey[:-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

    return d[lis_nestkey[-1]]  # get the value for the final key`
#enddef getnest

I think the Benedict library does this: python-benedict · PyPI

It has dynamic keyattr functionality which seems like what you’re looking for.

1 Like

See also glom:

By the way, this thread isn’t in the right category. I believe it should be moved to Ideas.