Blcknx
Blcknx

Reputation: 2431

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?

Upvotes: 21

Views: 12328

Answers (3)

PacifismPostMortem
PacifismPostMortem

Reputation: 365

I ran into an issue where I had a complex SimpleNamespace with SimpleNamespace within it, so I needed a recursive way to convert it into a dictionary. This gist was super helpful, since it converts the SimpleNamespace recursively.

def obj_to_dict(obj):
   if type(obj) is dict:
       res = {}
       for k, v in obj.items():
           res[k] = obj_to_dict(v)
       return res
   elif type(obj) is list:
       return [obj_to_dict(item) for item in obj]
   elif type(obj) is SimpleNamespace:
       return obj_to_dict(vars(obj))
   else:
       return obj

Upvotes: 1

pPanda_beta
pPanda_beta

Reputation: 648

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.

Upvotes: 3

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}

Upvotes: 39

Related Questions