Python: Recursively access dict via attributes as well as index access?
- by Luke Stanley
I'd like to be able to do something like this:
from dotDict import dotdictify
life = {'bigBang':
{'stars':
{'planets': []
}
}
}
dotdictify(life)
#this would be the regular way:
life['bigBang']['stars']['planets'] = {'earth': {'singleCellLife': {} }}
#But how can we make this work?
life.bigBang.stars.planets.earth = {'singleCellLife': {} }
#Also creating new child objects if none exist, using the following syntax
life.bigBang.stars.planets.earth.multiCellLife = {'reptiles':{},'mammals':{}}
My motivations are to improve the succinctness of the code, and if possible use similar syntax to Javascript for accessing JSON objects for efficient cross platform development.(I also use Py2JS and similar.)