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 |
Nice! But...
alex turtle:/tmp/2839610 [1012:1]% python -m doctest rget.py
**********************************************************************
File "rget.py", line 16, in rget.rget
Failed example:
rget(things, 'a', 'b', 'c', 'd')
Exception raised:
Traceback (most recent call last):
File "/usr/lib/python2.7/doctest.py", line 1254, in __run
compileflags, 1) in test.globs
File "<doctest rget.rget[4]>", line 1, in <module>
rget(things, 'a', 'b', 'c', 'd')
File "rget.py", line 20, in rget
return reduce(lambda d, key: d.get(key), args, dictionary)
File "rget.py", line 20, in <lambda>
return reduce(lambda d, key: d.get(key), args, dictionary)
AttributeError: 'str' object has no attribute 'get'
**********************************************************************
1 items had failures:
1 of 7 in rget.rget
***Test Failed*** 1 failures.```
What's "things"?
The doctest example variable?
If you want it to return None if it can't find the key or if it tries to access a keys of something that's not a dict, I'd just put the reduce in a try block.
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
def rget(dictionary, *args):
return reduce(lambda d, key: d.get(key), args, dictionary)