It has been asked: How to initialize a SimpleNamespace from a dict?
My question is for the opposite direction. How to initialize a dict from a SimpleNamespace?
Dictionaries are also initialized using the curly braces {} , and the key-value pairs are declared using the key:value syntax. You can also initialize an empty dictionary by using the in-built dict function. Empty dictionaries can also be initialized by simply using empty curly braces.
A class types.SimpleNamespace provides a mechanism to instantiate an object that can hold attributes and nothing else.
The setup is simple: the two different dictionaries - with dict() and {} - are set up with the same number of elements (x-axis). For the test, each possible combination for an update is run.
Python dict() Function The dict() function creates a dictionary. A dictionary is a collection which is unordered, changeable and indexed.
from types import SimpleNamespace
sn = SimpleNamespace(a=1, b=2, c=3)
vars(sn)
# returns {'a': 1, 'b': 2, 'c': 3}
sn.__dict__
# also returns {'a': 1, 'b': 2, 'c': 3}
The straightway dict wont work for heterogeneous lists.
import json
sn = SimpleNamespace(hetero_list=['aa', SimpleNamespace(y='ll')] )
json.loads(json.dumps(sn, default=lambda s: vars(s)))
This is the only way to get back the dict.
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