Convert nested Python dict to object?

Marc :

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?

Eli Bendersky :

Update: In Python 2.6 and onwards, consider whether the namedtuple data structure suits your needs:

>>> from collections import namedtuple
>>> MyStruct = namedtuple('MyStruct', 'a b d')
>>> s = MyStruct(a=1, b={'c': 2}, d=['hi'])
>>> s
MyStruct(a=1, b={'c': 2}, d=['hi'])
>>> s.a
1
>>> s.b
{'c': 2}
>>> s.c
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'MyStruct' object has no attribute 'c'
>>> s.d
['hi']

The alternative (original answer contents) is:

class Struct:
    def __init__(self, **entries):
        self.__dict__.update(entries)

Then, you can use:

>>> args = {'a': 1, 'b': 2}
>>> s = Struct(**args)
>>> s
<__main__.Struct instance at 0x01D6A738>
>>> s.a
1
>>> s.b
2

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

Converting a nested dict to Python object

Python - convert JSON object to dict

How to convert python nested dict to non-nested dict?

how to convert nested dict to dataframe using python?

Convert text file with 3 columns into nested dict of dict in Python

How do I convert a python object to (json) nested dict using the json module, without making a file-like object?

Convert sqlalchemy row object to python dict

Convert Json Dict object into DataFrame in Python

How to convert a Python dict to a Class object

How to convert python dict to DictRow object

Convert nested dict to dataframe

Python How to convert existing native dict to a custom dict object?

how to convert a python dict object to a java equivalent object?

How to convert a dict object in requests.models.Response object in Python?

Convert object attributes to dict

convert flat dict to nested list and dict and intersect this

how to convert a nested OrderedDict to dict?

How to convert a nested dict into dataframe

Convert pandas DataFrame to a nested dict

How to convert list to nested dict?

Convert Nested Dataframe In Dict To Dataframe

Parse nested Python dict

nested dict python keys

Threading in python with nested dict

Python : Generate nested dict

How to convert a string containing a list of dict into Python object?

How to convert string containing list of dictionaries to python (object) LIST of DICT

Nested dict to object with default value

"TypeError: Object of type int64 is not JSON serializable" while trying to convert a nested dict to JSON