19

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?

Blcknx
  • 1,921
  • 1
  • 12
  • 38
  • 8
    That is what `vars()` builtin function is for. – PaulMcG Oct 12 '18 at 16:53
  • I can't mark the answer as correct, if you place it here. :) – Blcknx Oct 12 '18 at 16:58
  • it's really weird that `dict(sn)` fails. See example and error: `dict(args) Traceback (most recent call last): File "/Users/brando/anaconda3/envs/automl-meta-learning/lib/python3.8/site-packages/IPython/core/interactiveshell.py", line 3343, in run_code exec(code_obj, self.user_global_ns, self.user_ns) File "", line 1, in dict(args) TypeError: 'types.SimpleNamespace' object is not iterable` – Charlie Parker Oct 16 '20 at 19:54

2 Answers2

35
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}
  • 2
    it's really weird that `dict(sn)` fails. See example and error: `dict(args) Traceback (most recent call last): File "/Users/brando/anaconda3/envs/automl-meta-learning/lib/python3.8/site-packages/IPython/core/interactiveshell.py", line 3343, in run_code exec(code_obj, self.user_global_ns, self.user_ns) File "", line 1, in dict(args) TypeError: 'types.SimpleNamespace' object is not iterable` – Charlie Parker Oct 16 '20 at 19:54
  • Try to do that for ``` sn = SimpleNamespace(hetero_list=['aa', SimpleNamespace(y='ll')] ) ``` It wont work – pPanda_beta Mar 02 '21 at 00:15
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.

pPanda_beta
  • 618
  • 7
  • 10