Skip to content

Instantly share code, notes, and snippets.

@mittenchops
Last active December 17, 2015 19: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 mittenchops/5664038 to your computer and use it in GitHub Desktop.
Save mittenchops/5664038 to your computer and use it in GitHub Desktop.
Lets you access nested dictionaries in Python the same way you access nested items in JSON notation. This means, however, that you cannot use dots in key names. Most useful for accessing named variables according to the results of variety.js.
def getByDot(obj, ref):
"""
Use MongoDB style 'something.by.dot' syntax to retrieve objects from Python dicts.
This also accepts nested arrays, and accommodates the '.XX' syntax that variety.js
produces.
Usage:
>>> x = {"top": {"middle" : {"nested": "value"}}}
>>> q = 'top.middle.nested'
>>> getByDot(x,q)
"value"
"""
val = obj
tmp = ref
ref = tmp.replace(".XX","[0]")
if tmp != ref:
print("Warning: replaced '.XX' with [0]-th index")
for key in ref.split('.'):
idstart = key.find("[")
embedslist = 1 if idstart > 0 else 0
if embedslist:
idx = int(key[idstart+1:key.find("]")])
kyx = key[:idstart]
try:
val = val[kyx][idx]
except IndexError:
print("Index: x['{}'][{}] does not exist.".format(kyx,idx))
raise
else:
val = val[key]
return(val)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment