Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get value from dictionary two levels deep

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"
   }
}
like image 668
JokerMartini Avatar asked Dec 13 '22 22:12

JokerMartini


1 Answers

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:]
like image 174
Michael Lorton Avatar answered Dec 16 '22 10:12

Michael Lorton