如何从字典初始化SimpleNamespace [英] How to initialize a SimpleNamespace from a dict
问题描述
我敢肯定这很简单,但是我找不到答案。
I'm sure this must be simple, but I could not find the answer.
我有一个像这样的字典:
I have a dictionary like:
d = {'a': 1, 'b':2}
我想通过点表示法来访问它,例如: da
I'd like to access that via dot notation, like: d.a
SimpleNamespace
是为此目的而设计的,但是我不能仅仅将字典传递给SimpleNamespace构造函数。
我收到错误: TypeError:预期没有位置参数
如何从中初始化SimpleNamespace
How do I initialize the SimpleNamespace from a dictionary?
推荐答案
使用 ** kwargs
调用语法将字典分解成单独的参数:
Pass in the dictionary using the **kwargs
call syntax to unpack your dictionary into separate arguments:
SimpleNamespace(**d)
这会将 d
中的每个键值对应用为单独的关键字参数。
This applies each key-value pair in d
as a separate keyword argument.
相反,密切相关的类定义 ** kwargs
参数定义
Conversely, the closely releated **kwargs
parameter definition in the __init__
method of the class definition shown in the Python documentation captures all keyword arguments passed to the class into a single dictionary again.
演示:
>>> from types import SimpleNamespace
>>> d = {'a': 1, 'b':2}
>>> sn = SimpleNamespace(**d)
>>> sn
namespace(a=1, b=2)
>>> sn.a
1
这篇关于如何从字典初始化SimpleNamespace的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!