动态设置深Python字典 [英] Dynamically set deep python dict

查看:61
本文介绍了动态设置深Python字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个列表,表示一个字典中的图层:

I have a list that represents the layers in a dict:

layers = ('layer1', 'layer2', 'layer3')

我要根据此动态创建一个字典,如下所示:

I want to dynamically create a dictionary out of this that looks like this:

data = {'layer1': {'layer2': {'layer3': ...}}}

我希望能够在三个点的位置插入一个值.我还希望能够使用layers列表动态访问此值.

I want to be able to insert a value at the position of the three dots. I also want to be able to dynamically access this value using the layers list.

推荐答案

因此,我提出了一个替代解决方案,该解决方案使用for循环而不是递归地调用该函数.我对这两种方法进行了基准测试,结果发现循环方法随着增加层和函数调用的数量而变得更快.

So I made an alternative solution that uses for loops instead of calling the function recursively. I benchmarked both approaches and the loop method turns out to be way faster as you increase the amount of layers and function calls.

def create_deep_dict(value, layers):

    orig_data = {}
    data = orig_data
    last_layer = layers[-1]

    for layer in layers[:-1]:
        data[layer] = {}
        data = data[layer]

    data[last_layer] = value

    return orig_data

def deep_dict_value(data, layers):

    for layer in layers:
        data = data[layer]

    return data

这篇关于动态设置深Python字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆