DEAR PEOPLE FROM THE FUTURE: Here's what we've figured out so far...

Welcome! This is a Q&A website for computer programmers and users alike, focused on helping fellow programmers and users. Read more

What are you stuck on? Ask a question and hopefully somebody will be able to help you out!
+2 votes

I want to do something like

if 'key' in dictionary:

but check multiple nested keys at once

if ['key_parent']['key_child']['key_grandchild'] in dictionary:

is this possible?


1 Answer

0 votes
Best answer

I'm afraid there isn't. The way to do it would be with try...except, like this:

    value = dictionary['key_parent']['key_child']['key_grandchild']
except KeyError:
    # no key

or multiple nested if:

value = None
if 'key_parent' in dictionary:
    if 'key_child' in dictionary['key_parent']:
        if 'key_grandchild' in dictionary['key_parent']['key_child']:
            value = dictionary['key_parent']['key_child']['key_grandchild']
selected by
Contributions licensed under CC0