-
-
Save obmarg/8360308 to your computer and use it in GitHub Desktop.
This file contains hidden or 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. | |
""" | |
import operator | |
def get_in(obj, *keys): | |
try: | |
return reduce(operator.getitem, keys, obj) | |
except (KeyError, IndexError): | |
return None | |
def main(): | |
obj = { | |
'one': 1, | |
'two': { | |
'one': 11 | |
}, | |
'three': [1, 2, 3] | |
} | |
assert 1 == get_in(obj, 'one') | |
assert 11 == get_in(obj, 'two', 'one') | |
assert 1 == get_in(obj, 'three', 0) | |
assert None == get_in(obj, 'four') | |
assert None == get_in(obj, 'two', 'three') | |
assert None == get_in(obj, 'three', 5) | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment