Explore Courses Blog Tutorials Interview Questions
0 votes
in Python by (47.6k points)

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?

1 Answer

0 votes
by (106k points)

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 you can do is you can use Bunch:-

What is Bunch:-

This is a library which is exclusively meant to provide attribute style access to dict objects and does exactly what the OP (OP is a class which defines a reference to a single operator) wants.

from bunch import bunchify

d = {'a': 1, 'b': {'c': 2}, 'd': ["hi", {'foo': "bar"}]}

x = bunchify(d)




Related questions

0 votes
2 answers
0 votes
1 answer
asked Oct 10, 2019 in Python by Sammy (47.6k points)
+1 vote
1 answer
0 votes
1 answer

Browse Categories