Python: Recursively access dict via attributes as well as index access?
Posted
by Luke Stanley
on Stack Overflow
See other posts from Stack Overflow
or by Luke Stanley
Published on 2010-06-13T05:42:01Z
Indexed on
2010/06/13
5:52 UTC
Read the original article
Hit count: 328
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.)
© Stack Overflow or respective owner