0 votes
1 view
in Python by (47.7k 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

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?

1 Answer

0 votes
by (107k 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)

X.a

X.b.c

x.d[1].foo 

Related questions

0 votes
1 answer
0 votes
2 answers
+1 vote
1 answer
0 votes
1 answer
asked Jul 2 in Python by Sammy (47.7k points)
Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...