python嵌套dict多键方法建议

问题描述 投票:0回答:1

显然,没有内置的 dict 方法(我们称之为

.nestkey
)用于多嵌套 dict 结构中的动态键寻址。在处理复杂的字典结构时,这可能要求很高,

例如,

dic_1.nestkey(list_of_keys_A) = value
而不是手动执行
dic_1["key_1"]["subkey_2"]["subsubkey_3"].. = value

不要将其与 1 级作业混淆:

dic_1["key_1"] = value_1, dic_2["key_2"] = value_2, ..

我知道避免嵌套结构通常是一个好的做法,但在必要时,动态寻址是强大的:

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

为此目的,我建议将

.nestkey
实现为内置
dict
方法。下面是如何用方法格式来表达它:

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
python dictionary dynamic nested multikey
1个回答
0
投票

由于没有 dict 内置方法,因此这里是函数格式(而不是方法格式)的解决方案。它已扩展为设置/获取各自的功能,即

fun_setnest
fun_getnest
,

def fun_setnest(dic, lis_nestkey, value): 
    d = dic
    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

    return dic
    
#enddef fun_setnest


def fun_getnest(dic, lis_nestkey, value): 
    d = dic
    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 fun_getnest
© www.soinside.com 2019 - 2024. All rights reserved.