Convert nested Python dict to object?

python dict to object recursive
python assign dict to object
convert dict to class object
python dict to object mapper
convert dictionary to object
nested dictionary python
python object from_dict
convert nested dictionary to list python

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
>>> x.b.c
>>> x.d[1].foo

I think, this is not possible without recursion, but what would be a nice way to get an object style for dicts?

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
>>> 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

The alternative (original answer contents) is:

class Struct:
    def __init__(self, **entries):

Then, you can use:

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

What is the most economical way to convert nested Python objects , an object's attributes, yielding a nested dictionary + list structure, with the ending points being python objects not having a __dict__ attribute� Let us see how to convert a given nested dictionary into an object. 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.

Surprisingly no one has mentioned Bunch. This library is exclusively meant to provide attribute style access to dict objects and does exactly what the OP wants. A demonstration:

>>> from bunch import bunchify
>>> d = {'a': 1, 'b': {'c': 2}, 'd': ["hi", {'foo': "bar"}]}
>>> x = bunchify(d)
>>> x.a
>>> x.b.c
>>> x.d[1].foo

A Python 3 library is available at - Credit goes to codyzu

Converting a nested dict to Python object, Maybe a recursive method like this - >>> class sample_token: def __init__(self, **response): for k,v in response.items(): if isinstance(v� Python dictionary: Exercise-27 with Solution. Write a Python program to convert a list into a nested dictionary of keys. Sample Solution:- . Python Code:

class obj(object):
    def __init__(self, d):
        for a, b in d.items():
            if isinstance(b, (list, tuple)):
               setattr(self, a, [obj(x) if isinstance(x, dict) else x for x in b])
               setattr(self, a, obj(b) if isinstance(b, dict) else b)

>>> d = {'a': 1, 'b': {'c': 2}, 'd': ["hi", {'foo': "bar"}]}
>>> x = obj(d)
>>> x.b.c
>>> x.d[1].foo

Convert nested Python dict to object?, To get an object style for dicts we have many methods some the important method I am discussing down here:- So the most important thing that� I have a nested OrderedDict I would like to convert to a dict. Applying dict() on it apparently only converts the outermost layer of the last entry. from collections import OrderedDict od =

x = type('new_dict', (object,), d)

then add recursion to this and you're done.

edit this is how I'd implement it:

>>> d
{'a': 1, 'b': {'c': 2}, 'd': ['hi', {'foo': 'bar'}]}
>>> def obj_dic(d):
    top = type('new', (object,), d)
    seqs = tuple, list, set, frozenset
    for i, j in d.items():
        if isinstance(j, dict):
            setattr(top, i, obj_dic(j))
        elif isinstance(j, seqs):
            setattr(top, i, 
                type(j)(obj_dic(sj) if isinstance(sj, dict) else sj for sj in j))
            setattr(top, i, j)
    return top

>>> x = obj_dic(d)
>>> x.a
>>> x.b.c
>>> x.d[1].foo

Convert nested Python dictionary to object, Let us see how to convert a given nested dictionary into an object. Method 1 : Using the json module. We can solve this particular problem by importing the json� I have tried converting the dict into a series object with the dates as index but that didn't match up the dates with the corresponding values for some reason. – anonuser0428 Sep 16 '13 at 21:04 the code has been posted.

There's a collection helper called namedtuple, that can do this for you:

from collections import namedtuple

d_named = namedtuple('Struct', d.keys())(*d.values())

In [7]: d_named
Out[7]: Struct(a=1, b={'c': 2}, d=['hi', {'foo': 'bar'}])

In [8]: d_named.a
Out[8]: 1

Python, Convert nested Python dictionary to object � Python - Convert Nested dictionary to Mapped Tuple � Python - Convert Flat dictionaries to Nested dictionary � Python - � The vars function will return a dictionary with ALL of the object members including the ones that were not wanted: sum and version. In some cases vars will work but it isn't really idiomatic python in my experience. Usually people are more explicit, saying "I am now casting my object to a dictionary" by doing e.g. obj.asdict().

Python dict to object (Example), A protip by lucho about python, structure, object, and dict. and the recursive call of DictToObject in _traverse will take care of any nested dicts. I am getting some nested output in format of Json dict object from a web service in python. The output is coming as nested Json dict Object. Now when I am trying to convert it into DataFrame in python the parentkey is not considered as column. I have five elements under one key. I want total 6 columns will appear in dataframe.

[Solved]-Python-Convert nested Python dict to object?, Wikitechy Forum is a community for learners to discus ideas, ask queries about Technologies and Career. Any Mapping (anything that behaves like a dictionary) can be passed into dict, and you will get a dict with the same contents. There is no need to iterate over it to construct it yourself. This gives you one loop, with one line in the body instead of a nested loop. But any code of the form:

recursively convert nested dicts to nested namedtuples, giving you , Lets you use dicts like they're JavaScript Object Literals (~=JSON). Storing data (like fixtures) in a structured way, in Python code If it's a mapping, convert. Python json.dumps() is an inbuilt function that converts the dictionary to string object, not the json(dictionary) object! so you have to load your string into a dict to use it by using the json.loads() method.

  • I was trying to do something similar recently, but a recurring dictionary key ("from" - which is a Python keyword) prevented me from going through with it. Because as soon as you tried using "x.from" to access that attribute you'd get a syntax error.
  • that's a problem indeed, but i can abandon on "from" to make life easier in accessing large dict constructs :) typing x['a']['d'][1]['foo'] is really annoying, so x.a.d[1].foo rules. if you need from, you can access it via getattr(x, 'from') or use _from as attribute instead.
  • from_ rather than _from according to PEP 8.
  • You can use getattr(x, 'from') instead of renaming the attribute.
  • Most of these "solutions" don't seem to work (even the accepted one, doesn't allow nested d1.b.c), I think it's clear you should be using something from a library, e.g. namedtuple from collections, as this answer suggests, ...
  • Same here - this is particularly useful for reconstructing Python objects from document oriented databases like MongoDB.
  • To get prettier printing add: def repr__(self): return '<%s>' % str('\n '.join('%s : %s' % (k, repr(v)) for (k, v) in self.__dict.iteritems()))
  • Will this work with nested dictionaries? and dicts containing objects and or list etc. Are there any catches?
  • @Sam S: it won't create nested Structs from nested dictionaries, but in general the type of the value can be anything. Key is restricted to being suitable for an object slot
  • -1 because a) it doesn't work for nested dicts, which the question clearly asked for, and b) the same functionality currently exists in standard libraries in argparse.Namespace (which has also defined __eq__, __ne__, __contains__).