Search code examples
pythondictionarynesteddefaultdict

Nested dictionary with default value on first key in Python


I want to create a nested dictionary in which when the first key provided is not in dictionary, it will fall back to a default value.

For example in the below code, I want to say the Banana sold is 17 (taking apple's dictionary whenever the first key is not in dictionary). Is this possible?

my_dict = {
    'apple': {
        Status.SUBMITTED: 15,
        Status.BLENDED: 16,
        Status.SOLD: 17
    },
    'orange': {
        Status.SUBMITTED: 105,
        Status.BLENDED: 109,
        Status.SOLD: 112
    }
}

my_dict.get('apple').get(Status.SOLD) 
17

my_dict.get('banana').get(Status.SOLD)
17

Solution

  • The get method has a default value argument to fall back on if the key argument isn't found in the dictionary. You can do something like:

    my_dict.get('banana', my_dict['apple']).get(Status.SOLD)