简体   繁体   中英

Get key from dict when value is another dict

I have an array of dictionaries, which are going to generate HTML forms dynamically.

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:

'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. ONE of those dictionaries (the first one in the list) has the string 'options' as a key, but the other does not. 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']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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