What is the difference between bunch and dictionary type in python?

Bunch is just like dictionary but it supports attribute type access.

  1. Data Type
  • 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

  1. 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.
    
  2. 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

  • Bunch() is useful serialization to json.
  • Bunch() is used to load data in sklearn. Here normally a bunch contains various attributes of various types(list, numpy array, etc.,).

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

Tags:

Python