Created
October 3, 2013 06:23
-
-
Save honza/6805825 to your computer and use it in GitHub Desktop.
Clojure's get-in in Python
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
""" | |
Clojure-inspired ``get_in`` function which gets value from nested dicts, | |
returning ``None`` if a key is not found. | |
""" | |
def get_in(obj, *keys): | |
for k in keys: | |
v = obj.get(k, None) | |
if not v: | |
return None | |
obj = v | |
return obj | |
def main(): | |
obj = { | |
'one': 1, | |
'two': { | |
'one': 11 | |
} | |
} | |
assert 1 == get_in(obj, 'one') | |
assert 11 == get_in(obj, 'two', 'one') | |
assert None == get_in(obj, 'three') | |
assert None == get_in(obj, 'two', 'three') | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
it should be
if v is None
what if you fetch a falsy value?