I found out that sklearn.utils.Bunch
and dict
work more or less the same. Like if there is a dict
object say
dict_1 = {"a":1, "b":2}
and a bunch object say bunch
bunch_1 = Bunch(a=1, b=2)
both have the same set of behaviour.
I found out that sklearn.utils.Bunch
and dict
work more or less the same. Like if there is a dict
object say
dict_1 = {"a":1, "b":2}
and a bunch object say bunch
bunch_1 = Bunch(a=1, b=2)
both have the same set of behaviour.
Bunch is a subclass of the Dict class and supports all the methods as dict does. In addition, it allows you to use the keys as attributes.
b = Bunch(a=1, b=2)
>>> b['b']
2
>>> b.b
2
Bunch is just like dictionary but it supports attribute type access.
Dictionary is in-built type, whereas Bunch is from bunchclass package. bunchclass.
Bunch works fine in python 2, but in python 3 it does not work! You import Bunch from sklearn.utils
from bunchclass import Bunch
# python 2
from sklearn.utils import Bunch
# python 3
Initialization
Initialization of bunch does not require {}
, but an explicit function with attributes of the elements you required to be in the bunch.
d1 = {'a':1, 'b':'one', 'c':[1,2,3], 4:'d'}`
b1 = Bunch(a=1, b='one', c=[1,2,3]) # Also note: here the keys of Bunch are
# attributes of the class. They must be
# mutable and also follow the
# conventions for variables.
Accessing the value of the key This is the main difference between the two.
d1['a']
b1['a']
b1.a
In a Bunch
, you can access the attributes using dot notations. In a dict
this is not possible.
Similarities Both Dictionary and bunch can contain values of any data type. But keys must be mutable. There can be nested dictionaries and nested bunches.
Utilities of Bunch
More on Bunch
as with any other object use dir(Bunch object)
to know more.
Refer to this link to know more about bunch:Bunch
In case your aim is to convert a bunch into dataframe, you can refer this link https://github.com/viswanathanc/basic_python/blob/master/sklearn.utils.bunch%20to%20pandas%20Dataframe.ipynb