Search code examples
pythondictionarykeyerror

How to deal with empty dict value


I have a json list in the form of a dictionary, and the following allows me to get values out of the dict:

valone = out['red']['blue']['green']

valtwo = out['purple']['yellow']['black']

From there I can run a conditional statement around valone or valtwo to see if they they are black of green.

Now this works very well, when those keys are populated, but when they are not I get

KeyError: 'black'

This is I can see as the value is empty.

I am having a hard time working out how to filter out before the declaration of the dict values.

I have seen people suggest

out.get("black", None)

But I cannot access black, as I its the third value I am after?


Solution

  • As you are using multi-level indexing, the cleanest way is to use exception to control the flow (which is quite accepted in Python though often frowned upon in other languages)

    try:
        valone = out['red']['blue']['green']
    except KeyError:
        # Handle Your Exception Here