0

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?

1 Answers1

1

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

Community
  • 1
  • 1
DineshKumar
  • 1,599
  • 2
  • 16
  • 30
  • thanks to @DineshKumar, with dictionary comprehension it works and each row has its own class instance – SuperMartingale Apr 05 '17 at 15:02
  • @SuperMartingale I am glad it helped. you may also use defaultdict is you wanna simplify the code. I will leave the implementation to you :) – DineshKumar Apr 05 '17 at 15:14