object - Python Two Dictionaries within another Dictionary within another Dictionary -


i'm trying create structure lend nicely parse log files. first tried setting dictionaries class objects, doesn't work since made them class attributes.

i'm trying following set structure:

#!/usr/bin/python class test:     def __init__(self):         __tbin = {'80':0, '70':0, '60':0, '50':0,'40':0}         __pbin = {}         __results = list()         info = {'tbin'   : __tbin.copy(),                 'pbin'   : __pbin.copy(),                 'results': __results}          self.writebuffer = list()         self.errorbuffer = list()          self.__tests = {'test1' : info.copy(),                         'test2' : info.copy(),                         'test3' : info.copy()}      def test(self):         self.__tests['test1']['tbin']['80'] += 1         self.__tests['test2']['tbin']['80'] += 1         self.__tests['test3']['tbin']['80'] += 1         print "test1: " + str(self.__tests['test1']['tbin']['80'])         print "test2: " + str(self.__tests['test2']['tbin']['80'])         print "test3: " + str(self.__tests['test3']['tbin']['80'])  test().test() 

my aim here create 2 dictionary objects (__tbin , __pbin) , making copies of them each test (i.e. test1 test2 test3...). however, experiencing test1, test2, , test3 still share same value when feel i'm explicitly making copies of them. above code includes how i'm testing i'm trying accomplish.

while expect see 1, 1, 1 printed, see 3, 3, 3 , can't figure out why, when explicitly 'copy()' on dictionaries.

i'm on python 2.7.4

for nested data structures need make deep copy instead of shallow copy. see here: http://docs.python.org/2/library/copy.html

import module copy @ beginning of file. replace calls info.copy() copy.deepcopy(info). so:

#!/usr/bin/python  import copy  class test:     def __init__(self):         ...         info = {'tbin'   : __tbin.copy(),                 'pbin'   : __pbin.copy(),                 'results': __results}         ...         self.__tests = {'test1' : copy.deepcopy(info),                         'test2' : copy.deepcopy(info),                         'test3' : copy.deepcopy(info)}      def test(self):         ...  ... 

Comments