python - 从dict递归设置对象属性
问题描述
我的问题比较简单:如何递归设置匹配字典键值对的对象属性?
例如,给定这个字典:
my_dict = {
"number": 0,
"thing": True,
"foo": {
"bar": {
"thing": "string"
}
}
}
我想用它的键作为属性递归地创建一个对象:
>>> my_obj = some_method(my_dict)
>>> my_obj.number
0
>>> my_obj.foo.bar
{"thing": "string"}
>>> my_obj.foo.bar.thing
"string"
解决方案
https://github.com/Infinidat/munch
该库旨在提供对字典的属性样式访问。
例如:
>>> from bunch import bunchify
>>> d = {'a': 1, 'b': {'c': 2}, 'd': ["hi", {'foo': "bar"}]}
>>> x = bunchify(d)
>>> x.a
1
>>> x.b.c
2
>>> x.d[1].foo
'bar'
推荐阅读
- python - 必须始终传递 `Layer.call` 的第一个参数。”
- linux - 通过 linux 中第二列中地点的 uniq 名称总结一列
- python - 如何在python中用i**2 + j**2的公式编写一个二维三角列表?
- javascript - 在需要考虑的参数过多的复杂应用程序中使用 react-router 时达到 URL 限制
- html - 水平对齐一行在移动设备上不换行的图像(按钮)
- reactjs - react-i18next 和 typescript 4.1
- c# - .Net 5 - Asp.Net 仍然没有 SynchronizationContext?
- python - 是否可以根据其他程序在 Mac OS 上执行的操作来运行脚本?
- json - scala中的JSON处理
- kotlin - Spring WebClient 阻塞线程