How to initialize a SimpleNamespace from a dict

Question:

I’m sure this must be simple, but I could not find the answer.

I have a dictionary like:

d = {'a': 1, 'b':2}

I’d like to access that via dot notation, like: d.a

The SimpleNamespace is designed for this, but I cannot just pass the dict into the SimpleNamespace constructor.
I get the error: TypeError: no positional arguments expected

How do I initialize the SimpleNamespace from a dictionary?

Asked By: MvdD

||

Answers:

Pass in the dictionary using the **kwargs call syntax to unpack your dictionary into separate arguments:

SimpleNamespace(**d)

This applies each key-value pair in d as a separate keyword argument.

Conversely, the closely related **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.

Demo:

>>> from types import SimpleNamespace
>>> d = {'a': 1, 'b':2}
>>> sn = SimpleNamespace(**d)
>>> sn
namespace(a=1, b=2)
>>> sn.a
1
Answered By: Martijn Pieters
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.