Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to initialize a SimpleNamespace from a dict [duplicate]

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?

like image 925
MvdD Avatar asked May 11 '18 15:05

MvdD


People also ask

What is SimpleNamespace in python?

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.

What is a dict constructor?

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.

Can a dict contain a dict?

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.

What is dict constructor in python?

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.


1 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 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
like image 136
Martijn Pieters Avatar answered Sep 17 '22 15:09

Martijn Pieters