简体   繁体   English

Python通过变量中的键获取/设置dicts的dict值

[英]Python get/set value of dict of dicts by key in variable

I have dict of dicts in Python, it can be deep, not just 2 levels.我在 Python 中有字典字典,它可以很深,而不仅仅是 2 个级别。

data = {
    0: {
        1: {
            2: "Yes"
        },
        3: {
            4: "No"
        }
    },
}

I need to get and set the data, but the key is dynamic and is stored in list我需要获取和设置数据,但密钥是动态的并存储在列表中

key_to_get = [0,1,2]

print(data.get(key_to_get))

Should print Yes应该打印Yes

Ideas?想法?

Here is a simple recursive function which solves the problem这是一个解决问题的简单递归函数

def getValue(dict, keys):
    if len(keys) == 1:
        return dict.get(keys[0])
    return getValue(dict.get(keys[0]), keys[1:])

And an iterative approach if you're boring如果你很无聊,还有一个迭代方法

temp = data
for key in key_to_get:
    temp = temp.get(key)
print(temp)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM