SuperMartingale
SuperMartingale

Reputation: 57

Python dictionary set all values to class object

After having created a dictionary from one dataframe column as keys, I want to set all values to an instance of an object (the class serves as container for storing key statistics for each row of the original pandas dataframe).

Hence, I tried this:

class Bond:
    def __init__(self):
        self.totalsize = 0
        self.count = 0

if __name__ == '__main__':

    isin_dict = list_of_isins.set_index('isin').T.to_dict()
    isin_dict = dict.fromkeys(isin_dict, Bond())

The problem is that all values in isin_dict point to the same address, ie all rows share the same Bond class object. How could I create a dictionary with each key holding a separate class instance as value?

Upvotes: 0

Views: 1529

Answers (1)

DineshKumar
DineshKumar

Reputation: 1739

The reason for this is already explained here

dict.fromKeys() uses the same value for every key.

The solution is to use dictionary comprehensions or to use defaultdict from collections module.

Sample Code to use defaultdict

from collections import defaultdict    

class Bond:

    def __init__(self):
        pass        

# I have just used your variable and stored in a list
d = defaultdict(lambda : list(list_of_isins.set_index('isin').T)    

for keys in d:
    d[keys] = Bond() 

print (d)

The reason we are passing the type dict to defaultdict is the first argument should be callable for defaultdict. Else you may get a TypeError

Alternately you may also pass a lambda expression which will make it callable

Upvotes: 1

Related Questions