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?
Python's SimpleNamespace class provides an easy way for a programmer to create an object to store values as attributes without creating their own (almost empty) class.
The dict() constructor creates a dictionary in Python. Different forms of dict() constructors are: class dict(**kwarg) class dict(mapping, **kwarg) class dict(iterable, **kwarg) Note: **kwarg let you take an arbitrary number of keyword arguments. A keyword argument is an argument preceded by an identifier (eg.
A dictionary variable can store another dictionary in nested dictionary. The following example shows how nested dictionary can be declared and accessed using python. Here, 'courses' is a nested dictionary that contains other dictionary of three elements in each key.
Python dict () The dict() python function is a constructor that is used to create dictionaries. Dictionary is a data structure in Python that contains elements in the form of a value and its respective key.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With