Created
May 30, 2012 23:48
-
-
Save agonzalezro/2839610 to your computer and use it in GitHub Desktop.
Do a recursive get over the keys of nested dictionaries
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.