I'm searching for an elegant way to get data using attribute access on a dict with some nested dicts and lists (i.e. javascript-style object syntax).
For example:
>>> d = {'a': 1, 'b': {'c': 2}, 'd': ["hi", {'foo': "bar"}]}
Should be accessible in this way:
>>> x = dict2obj(d)
>>> x.a
1
>>> x.b.c
2
>>> x.d[1].foo
bar
I think, this is not possible without recursion, but what would be a nice way to get an object style for dicts?
How about this:
This can then be used like this:
Old Q&A, but I get something more to talk. Seems no one talk about recursive dict. This is my code:
Can be used with any sequence/dict/value structure of any depth.
I know there's already a lot of answers here already and I'm late to the party but this method will recursively and 'in place' convert a dictionary to an object-like structure... Works in 3.x.x
This also works well too
Building off my answer to "python: How to add property to a class dynamically?":
You call
makedata
on the dictionary you want converted, or maybetrydata
depending on what you expect as input, and it spits out a data object.Notes:
trydata
if you need more functionality.x.a = {}
or similar.