Skip to content

Instantly share code, notes, and snippets.

@leighklotz
Created April 14, 2016 00:05
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 leighklotz/2017533262f7532f1cd7e27185bf5f9e to your computer and use it in GitHub Desktop.
Save leighklotz/2017533262f7532f1cd7e27185bf5f9e to your computer and use it in GitHub Desktop.
bare-bones xpath-like navigator for python dict
# -*-PYTHON-*-
from __future__ import print_function
def nav(d, ks):
def nav2(d, ks):
if len(ks) == 0:
return d
if not isinstance(d, dict):
raise KeyError(ks)
if ks[0] not in d:
return None
return nav2(d[ks[0]], ks[1:])
return nav2(d, ks.split('.'))
if __name__ == "__main__":
assert(nav({'a': {'b': {'c': 3}}}, 'a.b.c') == 3)
try:
x = nav({'a': {'b': {'c': 3}}}, 'a.b.c.d')
except KeyError:
pass
assert(nav({'a': {'b': {'c': 3}}}, 'a.b') == {'c': 3})
assert(nav({'a': {'b': ['c', 3]}}, 'a.b') == ['c', 3])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment