Skip to content

Instantly share code, notes, and snippets.

@thorwhalen
Last active October 17, 2019 14:20
Show Gist options
  • Save thorwhalen/cdb8521952dae638466a3b79db9f67ac to your computer and use it in GitHub Desktop.
Save thorwhalen/cdb8521952dae638466a3b79db9f67ac to your computer and use it in GitHub Desktop.
Lambda function to get an element in a nested dict, specifying a dot separated key path (and generalization to any separator and method)
from functools import reduce
# The simple dotpath version
dotpath_get = lambda d, dotpath: reduce(lambda x, y: x.get(y), dotpath.split('.'), d)
# A generalization to any separator and any "get" method:
keypath_get = lambda d, keypath, sep, getmethod: reduce(lambda x, y: getattr(x, getmethod)(y), keypath.split(sep), d)
@thorwhalen
Copy link
Author

thorwhalen commented Oct 17, 2019

Usage

>>> assert dotpath_get(d, 'a.b')
3
>>> import os
>>> assert keypath_get(os, 'path.sep', '.', '__getattribute__') == os.path.sep
>>> assert keypath_get(os, 'path/curdir', '/', '__getattribute__') == os.path.curdir
>>> assert keypath_get(os, 'path,exists,__annotations__', ',', '__getattribute__') == os.path.exists.__annotations__

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