Sometimes, we want to convert a nested Python dict to an object.
In this article, we’ll look at how to convert a nested Python dict to an object.
How to convert a nested Python dict to an object?
To convert a nested Python dict to an object, we can use the bunch
library.
To install it, we run
pip install bunch
Then we use it by writing
from bunch import bunchify
d = {"a": 1, "b": {"c": 2}, "d": ["hi", {"foo": "bar"}]}
x = bunchify(d)
to call bunchify
with dict d
to return the dict’s content on an object.
Then we can use x.a
to access the value of d
with key 'a'
.
And we can use x.b.c
to access the entry with key 'c'
in the dict d
with key 'b'
.
Conclusion
To convert a nested Python dict to an object, we can use the bunch
library.