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?
Wanted to upload my version of this little paradigm.
It preserves the attributes for the type that's imported into the class. My only concern would be overwriting methods from within the dictionary your parsing. But otherwise seems solid!
Taking what I feel are the best aspects of the previous examples, here's what I came up with:
Update: In Python 2.6 and onwards, consider whether the
namedtuple
data structure suits your needs:The alternative (original answer contents) is:
Then, you can use:
There's a collection helper called
namedtuple
, that can do this for you:You can leverage the
json
module of the standard library with a custom object hook:Example usage:
And it is not strictly read-only as it is with
namedtuple
, i.e. you can change values – not structure: