python - dictionary within a dictionary -


i trying create dictionary within dictionary dictionaries end same details.

here's code:

class dailystatement(object):   def __init__(self):      self.masterdict={}      self.subdict={}      self.list_of_subdicts=['yesterday','today']       self.keys=['high','low','open','close']      self._create_masterdict()    def _create_masterdict(self):      subdict in self.list_of_subdicts:        self.masterdict[subdict]={}        self.masterdict[subdict]=self.create_subdict(subdict)        print self.masterdict[subdict]    def create_subdict(self,subdict):      item in self.keys:        subdict[item]=self.get_value(item,subdict)      return self.subdict    def get_value(self,item,subdict):      {code find value}      return value 

when run:

ds=dailystatement() 

it prints fine , seems working perfectly, showing on console:

 {'high':2,'low':1,'open':1.5,'close':1.6}  {'high':2.2,'low':2.1,'open':2.5,'close':2.6} 

but when run:

print ds.masterdict 

i get:

{'today':{'high':2,'low':1,'open':1.5,'close':1.6},  'yesterday':{'high':2,'low':1,'open':1.5,'close':1.6}} 

i can't understand why is. seems build masterdict fine when initiating class, after code runs dictionary rewriting itself?

i have been looking @ problem past few hours , can't seem figure out.

any appreciated.

you using self.subdict both of sub dictionaries. should doing creating new sub dictionary every time need one:

import random  class dailystatement(object):  # changed c c   def __init__(self):  # added self      self.masterdict={}      # removed self.subdict      self.list_of_subdicts=['yesterday', 'today']       self.keys=['high', 'low', 'open', 'close']      self._create_masterdict()    def _create_masterdict(self):      subdict in self.list_of_subdicts:        self.masterdict[subdict] = {}        self.masterdict[subdict] = self.create_subdict(subdict)  # added self        print self.masterdict[subdict]    def create_subdict(self, subdict):      sub_dict = {}      item in self.keys:         sub_dict[item] = self.get_value(item, subdict)  # added self      return sub_dict      def get_value(self, item, subdict):  # added self      return random.randrange(1,4)  if __name__ == "__main__":   ds=dailystatement()   print ds.masterdict 

i've left comments on other changes.

here simple example in python repl:

python 2.7.9 (default, dec 10 2014, 12:24:55) [msc v.1500 32 bit (intel)] on win32 type "help", "copyright", "credits" or "license" more information. >>> y = {} >>> x = y >>> y["noel"] = "rocks" >>> x {'noel': 'rocks'} >>> 

as can observe x has never been directly set still contains key , value added y.


Comments