Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert nested Python dict to object?

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?

like image 308
Marc Avatar asked Aug 20 '09 11:08

Marc


People also ask

How do you convert a dictionary to an object in Python?

Method 1 : Using the json module. We can solve this particular problem by importing the json module and use a custom object hook in the json. loads() method.

Is a Python dictionary an object?

Python provides another composite data type called a dictionary, which is similar to a list in that it is a collection of objects.

What is the __ dict __ attribute of an object in Python?

A special attribute of every module is __dict__. This is the dictionary containing the module's symbol table. A dictionary or other mapping object used to store an object's (writable) attributes.

What is Python munch?

A Munch is a Python dictionary that provides attribute-style access (a la JavaScript objects).


1 Answers

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 
like image 180
Eli Bendersky Avatar answered Sep 21 '22 07:09

Eli Bendersky