通过属性递归访问字典以及索引访问?
我希望能够做这样的事情:
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':{}}
我的动机是提高代码的简洁性,如果可能的话,使用与 Javascript 类似的语法来访问 JSON 对象,以实现高效的跨平台开发。 (我也使用 Py2JS 和类似的。)
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.)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
以下是创造这种体验的一种方法:
Here's one way to create that kind of experience:
下面是嵌套属性字典的另一个实现(受到 Curt Hagenlocher 答案的启发,精简到必要的部分):
这在 Python 2 和 3 中都有效:
在 Python3 中需要将 KeyError 转换为 __getattr__ 中的 AttributeError这样
hasattr
在找不到属性的情况下也可以工作:Below another implementation of a nested attribute dictionary (inspired by the answer of Curt Hagenlocher, stripped down to the essential):
This works in both Python 2 and 3:
Converting KeyError into AttributeError in
__getattr__
is required in Python3 such thathasattr
works also in case the attribute is not found:有一个包可以完全满足您的需求,而且还可以做更多的事情,它被称为 Prodict。
PS:我是该产品的作者。
There is a package doing exactly what you want and also something more and it is called Prodict.
PS: I'm the author of the Prodict.
这是另一个解决方案:
然后在 python 控制台中:
打印正确的值
Here is another solution:
Then in the python console:
prints the correct values