Skip to content

Instantly share code, notes, and snippets.

@honza
Created October 3, 2013 06:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save honza/6805825 to your computer and use it in GitHub Desktop.
Save honza/6805825 to your computer and use it in GitHub Desktop.
Clojure's get-in in Python
"""
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()
@brainkim
Copy link

it should be if v is None what if you fetch a falsy value?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment