【问题标题】:How to initialize a dict from a SimpleNamespace?如何从 SimpleNamespace 初始化字典?
【发布时间】:2018-10-12 16:50:32
【问题描述】:

已询问:How to initialize a SimpleNamespace from a dict?

我的问题是相反的方向。如何从 SimpleNamespace 初始化 dict?

【问题讨论】:

  • 这就是 vars() 内置函数的用途。
  • 如果您将答案放在这里,我无法将其标记为正确。 :)
  • dict(sn) 失败真的很奇怪。查看示例和错误:dict(args) Traceback (most recent call last): File "/Users/brando/anaconda3/envs/automl-meta-learning/lib/python3.8/site-packages/IPython/core/interactiveshell.py", line 3343, in run_code exec(code_obj, self.user_global_ns, self.user_ns) File "<ipython-input-5-1bf3c62db268>", line 1, in <module> dict(args) TypeError: 'types.SimpleNamespace' object is not iterable

标签: python python-3.x


【解决方案1】:
from types import SimpleNamespace

sn = SimpleNamespace(a=1, b=2, c=3)

vars(sn)
# returns {'a': 1, 'b': 2, 'c': 3}

sn.__dict__
# also returns {'a': 1, 'b': 2, 'c': 3}

【讨论】:

  • dict(sn) 失败真的很奇怪。查看示例和错误:dict(args) Traceback (most recent call last): File "/Users/brando/anaconda3/envs/automl-meta-learning/lib/python3.8/site-packages/IPython/core/interactiveshell.py", line 3343, in run_code exec(code_obj, self.user_global_ns, self.user_ns) File "<ipython-input-5-1bf3c62db268>", line 1, in <module> dict(args) TypeError: 'types.SimpleNamespace' object is not iterable
  • 尝试为 ``` sn = SimpleNamespace(hetero_list=['aa', SimpleNamespace(y='ll')] ) ``` 它不会工作
【解决方案2】:

直接 dict 不适用于异构列表。

import json

sn = SimpleNamespace(hetero_list=['aa', SimpleNamespace(y='ll')] )
json.loads(json.dumps(sn, default=lambda s: vars(s)))

这是取回字典的唯一方法。

【讨论】:

    猜你喜欢
    • 2018-10-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-20
    • 2016-02-14
    • 2016-11-20
    相关资源
    最近更新 更多