What is an elegant way of getting the value for a sub-key inside a dictionary, but only if the two levels of keys exist using python?
For example I want to get the value for 'team' from 'dad'. So if Dad doesn't exist it should return none, otherwise continue to look for subkey 'team' and if that doesn't exist return none, otherwise return the value.
Would there be an easy way to possibly write a recursive function which i just pass an array of names which it then looks through and if it hits a missing key it just returns a defined default value.
i know i can currently do
dict.get('dad', None)
I'd like to be able to do something like this
dict.get(['dad','team'], None)
dict
{
"dad":{
"team":"packers"
},
"mom":{
"show":"rugrats",
"vehicle":"buggy"
}
}
dict.get('dad', {}).get('team', None)
That does exactly two levels. In the general case, you could
def recurGet(d, ks):
head, *tail = ks
return recurGet(d.get(head, {}), tail) if tail else d.get(head)
The head, *tail = ks
is Python 3. In Python 2, you would have to write it explicitly as
head = ks[0]
tail = ks[1:]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With