18

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?

jpp
  • 159,742
  • 34
  • 281
  • 339
MvdD
  • 22,082
  • 8
  • 65
  • 93
  • 1
    recursive solutions: [Creating a namespace with a dict of dicts](https://stackoverflow.com/questions/50490856/creating-a-namespace-with-a-dict-of-dicts) and [How to convert a nested python dictionary into a simple namespace?](https://stackoverflow.com/questions/66208077/how-to-convert-a-nested-python-dictionary-into-a-simple-namespace) – milahu May 09 '22 at 13:17

1 Answers1

47

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
Stagg
  • 2,660
  • 5
  • 34
  • 32
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343