【问题标题】:Recursively set object attributes from dict [duplicate]从dict递归设置对象属性[重复]
【发布时间】:2021-05-01 15:32:42
【问题描述】:

我的问题比较简单:如何递归设置匹配字典键值对的对象属性?

例如,给定这个字典:

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" 

【问题讨论】:

标签: python dictionary recursion


【解决方案1】:

另一种使用内置库的方式:

import json
from types import SimpleNamespace

my_dict = {
    "number": 0,
    "thing": True,
    "foo": {
        "bar": {
            "thing": "string"
        }
    }
}

dumped_data = json.dumps(my_dict)
result = json.loads(dumped_data, object_hook=lambda x: SimpleNamespace(**x))

result.number

>> 0

result.foo.bar.thing

>> string

【讨论】:

    【解决方案2】:

    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'
    

    【讨论】:

    • 当然有这类东西的库,只是用谷歌搜索找不到,谢谢!
    • 你在讽刺吗?
    • 你想让我说我在讽刺吗?没有权利?那么不,我不是在讽刺。
    猜你喜欢
    • 1970-01-01
    • 2019-07-20
    • 2021-01-01
    • 2020-11-18
    • 1970-01-01
    • 2021-12-31
    • 2018-03-28
    • 2012-12-31
    • 1970-01-01
    相关资源
    最近更新 更多