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.
A Bunch is a Python dictionary that provides attribute-style access (a la JavaScript objects). Bunch acts like an object and a dict.
Both of these are tools used in the Python language, but there is a crucial difference between List and Dictionary in Python. A list refers to a collection of various index value pairs like that in the case of an array in C++. A dictionary refers to a hashed structure of various pairs of keys and values.
A dictionary is an arbitrary mapping. An object is a special mapping from names to variables and methods. A class is a language construct that gathers together objects with similar structure and helps to create objects. Objects and classes can be simulated in a straightforward way using functions and dictionaries.
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
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
Read more here
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With