Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to initialize a dict from a SimpleNamespace?

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?

like image 785
Blcknx Avatar asked Oct 12 '18 16:10

Blcknx


People also ask

How do you initiate a dictionary?

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.

What is SimpleNamespace in python?

A class types.SimpleNamespace provides a mechanism to instantiate an object that can hold attributes and nothing else.

Is dict () the same as {}?

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.

What is the dict () function in python?

Python dict() Function The dict() function creates a dictionary. A dictionary is a collection which is unordered, changeable and indexed.


2 Answers

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}
like image 70
Николай Гордеев Avatar answered Sep 17 '22 07:09

Николай Гордеев


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.

like image 45
pPanda_beta Avatar answered Sep 18 '22 07:09

pPanda_beta