python dictionary weird behavior -


  1. i can't understand why, when c=2 , c=3, dict2['a']=1 , dict2['a']=4 respectively , not 0, though make dict2 equal dict1, dict1['a']=0? why dict1['a'] change 0? don't change of dict1 variables!
  2. why dict3 show correct values within loop, shows values last iteration 3 after loop finished.

thank much.

import collections  def main():       dict1 = collections.ordereddict()     dict2 = collections.ordereddict()     dict3 = collections.ordereddict()      dict1['a'] = 0     dict1['b'] = 0     dict1['c'] = 0      c in [1, 2, 3]:         print('c=' + str(c))         dict2 = dict1         print('dict1a=' + str(dict1['a']))         print('dict2a=' + str(dict2['a']))         if c == 1:             dict2['a'] = 1             dict2['b'] = 2             dict2['c'] = 3         elif c ==2:             dict2['a'] = 4             dict2['b'] = 5             dict2['c'] = 6         elif c ==3:             dict2['a'] = 7             dict2['b'] = 8             dict2['c'] = 9         dict3['c' + str(c)] = dict2         print('dict2a=' + str(dict2['a']))         print('dict' + str(c) + 'a=' + str(dict3['c' + str(c)]['a']))         print('dict' + str(c) + 'b=' + str(dict3['c' + str(c)]['b']))         print('dict' + str(c) + 'c=' + str(dict3['c' + str(c)]['c']))      print('dict3-c1a='+ str(dict3['c1']['a']))     print('dict3-c2b=' + str(dict3['c2']['b']))     print('dict3-c3c=' + str(dict3['c3']['c']))  if __name__ == '__main__':     main() 

output:

c=1 dict1a=0 dict2a=0 dict2a=1 dict1a=1 dict1b=2 dict1c=3 c=2 dict1a=1 dict2a=1 dict2a=4 dict2a=4 dict2b=5 dict2c=6 c=3 dict1a=4 dict2a=4 dict2a=7 dict3a=7 dict3b=8 dict3c=9 dict3-c1a=7 dict3-c2b=8 dict3-c3c=9 

* edit * thank answers. didn't know '=' operation dictionaries not same variables. found out , suggested g.d.d.c, copy() wanted:

        dict2 = dict1.copy() 

when assign dict2 = dict1 replace name existed empty ordereddict , tell interpreter instead use dict2 refer same object exists in name dict1. can couple of things work around this:

# copy dict2 = dict1.copy() # update dict 2 dict2.update(dict1.iteritems()) 

Comments

Popular posts from this blog

html - How to style widget with post count different than without post count -

How to remove text and logo OR add Overflow on Android ActionBar using AppCompat on API 8? -

javascript - storing input from prompt in array and displaying the array -