Skip to content

Instantly share code, notes, and snippets.

@obmarg
Forked from honza/get.py
Last active January 2, 2016 20:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save obmarg/8360308 to your computer and use it in GitHub Desktop.
Save obmarg/8360308 to your computer and use it in GitHub Desktop.
"""
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