首页 > 解决方案 > 从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" 

标签: pythondictionaryrecursion

解决方案


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'

推荐阅读