0

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
ArMonk
  • 366
  • 6
  • 13
  • Does this answer your question? [Why dict.get(key) instead of dict\[key\]?](https://stackoverflow.com/questions/11041405/why-dict-getkey-instead-of-dictkey) – dspencer Mar 11 '20 at 04:15

1 Answers1

2

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)
Scratch'N'Purr
  • 9,959
  • 2
  • 35
  • 51