Last active
June 2, 2024 12:17
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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