2

I am dealing with JSON data sets with dynamic response structures (keys) and need to execute code if certain keys exist. Right now if the key doesn't exist it throws a key error which I have attempted to pass through a bool operand but it appears the key error trumps bool operands in Python.

bool(dictionary['key'])

KeyError: 'key'

I feel like there is some way to do this that's easier than I'm attempting but just haven't been able to find anything through researching. Any help would be greatly appreciated.

0

4 Answers 4

9

You want dictionary.get('key'). By default, this returns None, which will evaluate as False.

Sign up to request clarification or add additional context in comments.

5 Comments

That is a great method for when a dictionary is shallow however JSON data sets can be heavily layered and I need something that iterates through the entire data structure to check for keys 2 or 3 levels deep at times. Is there a simple way to do that?
@JackBurton try / except KeyError: might be useful for that.
@JackBurton Do you mean that you want a function to recursively check for a key? That's significantly more complex, and you probably don't want that sort of search everytime you want the key value.
@RushyPanchal Correct. The JSON structure is like this: {dictionary1 {dictionary2 [list {dictionary3}] } } I am after the keys in dictionary3 which may or may not exist for each item in the list. There could be several iterations of dictionary3 within the list object.
Jack: You need to show the structure of the dictionary being searched and revise your question (and its title) to reflect your real question.
1

use dict.get and set a default value if the key was not found

dictionary.get('key', 'NotFound')

Comments

0

Have you tried using dictionary.has_key(key_name) this method will return true if the key exists and false if it doesn't.

1 Comment

Better use key_name in dictionary test.
-1

Did you want something like this?

#!python3
json_data = [
        { 'key1':
            { 'key2':
                [
                    {'key3': 1 }
                    ]
                }
            }
        ]

def get_deep(*keys):
    try:
        doa = json_data
        for key in keys:
            doa = doa[key]
        return doa
    except KeyError:
        return None
    except IndexError:
        return None

tests = (
    # Want, Keys...
    (1, 0, 'key1', 'key2', 0, 'key3'),
    (None, 1, 'key1', 'key2', 0, 'key3'),
    (None, 0, 'key11', 'key2', 0, 'key3'),
    (None, 0, 'key1', 'key22', 0, 'key3'),
    (None, 0, 'key1', 'key2', 1, 'key3'),
    (None, 0, 'key1', 'key2', 0, 'key33'),
)


for i,test in enumerate(tests):
    expected,*keys = test
    got = get_deep(*keys)
    if got is expected:
        print(i, "OK")
    else:
        print(i, "FAIL", got, "is not", expected)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.