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:
JavaScript
x
2
1
>>> d = {'a': 1, 'b': {'c': 2}, 'd': ["hi", {'foo': "bar"}]}
2
Should be accessible in this way:
JavaScript
1
8
1
>>> x = dict2obj(d)
2
>>> x.a
3
1
4
>>> x.b.c
5
2
6
>>> x.d[1].foo
7
bar
8
I think, this is not possible without recursion, but what would be a nice way to get an object style for dicts?
Advertisement
Answer
Update: In Python 2.6 and onwards, consider whether the namedtuple
data structure suits your needs:
JavaScript
1
16
16
1
>>> from collections import namedtuple
2
>>> MyStruct = namedtuple('MyStruct', 'a b d')
3
>>> s = MyStruct(a=1, b={'c': 2}, d=['hi'])
4
>>> s
5
MyStruct(a=1, b={'c': 2}, d=['hi'])
6
>>> s.a
7
1
8
>>> s.b
9
{'c': 2}
10
>>> s.c
11
Traceback (most recent call last):
12
File "<stdin>", line 1, in <module>
13
AttributeError: 'MyStruct' object has no attribute 'c'
14
>>> s.d
15
['hi']
16
The alternative (original answer contents) is:
JavaScript
1
4
1
class Struct:
2
def __init__(self, **entries):
3
self.__dict__.update(entries)
4
Then, you can use:
JavaScript
1
9
1
>>> args = {'a': 1, 'b': 2}
2
>>> s = Struct(**args)
3
>>> s
4
<__main__.Struct instance at 0x01D6A738>
5
>>> s.a
6
1
7
>>> s.b
8
2
9