简体   繁体   English

当值是另一个dict时从dict获取密钥

[英]Get key from dict when value is another dict

I have an array of dictionaries, which are going to generate HTML forms dynamically. 我有一系列字典,这些字典将动态生成HTML表单。

form_elements = [
{
    'input_type': 'radio',
    'options':
    {
        'bad': 'Bad',
        'good': 'Good'
    },
    'caption': 'How are you feeling?'
},
{
    'input_type': 'input_text',
    'caption': 'What is your name?'
}]

When I iterate over the list and try to get the options for my radio-button, I get a key error, presumably because the value is another dictionary. 当我遍历该列表并尝试获取单选按钮的选项时,出现键错误,可能是因为该值是另一个字典。

for elm in form_elements:
    print elm['options']

Strangely though, this returns true: 奇怪的是,这返回true:

'options' in elm.keys()

How can I get access to the nested dictionary? 如何获得嵌套字典?

When you're iterating over form_elements , you're iterating over a list that contains two dictionaries. 当您遍历form_elements ,您遍历了包含两个字典的列表。 ONE of those dictionaries (the first one in the list) has the string 'options' as a key, but the other does not. 这些词典中的一个(列表中的第一个)以字符串“ options”作为键,而另一个则没有。 So it succeeds on the first loop, but fails on the second loop. 因此,它在第一个循环上成功,但在第二个循环上失败。 If you look right above the stack trace, you should see the successful print statement. 如果您在堆栈跟踪上方看,应该会看到成功的打印语句。

It's not a problem to have a dictionary as a value for a dictionary. 将字典作为字典的值不是问题。

Try this: 尝试这个:

for elm in form_elements:
    if 'options' in elm.keys():
        print elm['options']

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

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