Skip to content

Instantly share code, notes, and snippets.

@agonzalezro
Created May 30, 2012 23:48
Show Gist options
  • Save agonzalezro/2839610 to your computer and use it in GitHub Desktop.
Save agonzalezro/2839610 to your computer and use it in GitHub Desktop.
Do a recursive get over the keys of nested dictionaries
# I always have problems with the names, please help me :)
def rget(dictionary, *args):
'''Recursive `.get()` function.
Do a recursive get over the keys of nested dictionaries.
>>> things = {'a': {'b': {'c': 'd'}}}
>>> rget(things, 'a', 'b', 'c')
'd'
>>> rget(things, 'a', 'b')
{'c': 'd'}
>>> rget(things, 'a')
{'b': {'c': 'd'}}
>>> rget(things, 'a', 'b', 'c', 'd')
>>> rget(things, 'fake_key')
>>> rget(things, 'a', 'fake_key')
'''
to_be_returned = None
if args[1:]:
to_be_returned = rget(dictionary.get(args[0]), *args[1:])
elif args[0:] and isinstance(dictionary, dict):
to_be_returned = dictionary.get(args[0])
return to_be_returned
@agonzalezro
Copy link
Author

FTR because we've already talked about this by chat.

This is exactly what I'm trying to avoid, the need of use try-except blocks or nested ifs.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment