10

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
  • 147,904
  • 31
  • 244
  • 302
MvdD
  • 20,035
  • 6
  • 59
  • 89
  • 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) – Mila Nautikus May 09 '22 at 13:17

1 Answers1

29

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 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.

Demo:

>>> from types import SimpleNamespace
>>> d = {'a': 1, 'b':2}
>>> sn = SimpleNamespace(**d)
>>> sn
namespace(a=1, b=2)
>>> sn.a
1
Martijn Pieters
  • 963,270
  • 265
  • 3,804
  • 3,187