0
a = defaultdict(int) 
a = a.fromkeys(["a","b","c"],[0,0])
print a
i = 1
j = 1
for k in a.keys():
    print a
    print a[k][0], a[k][1]
    a[k][0] += i
    a[k][1] += j
    i += 1
    j = i*2
print a

In the output, it is showing that all keys are updated for each iteration in the loop, instead of the key for the particular iteration. This is the output:

defaultdict(None, {'a': [0, 0], 'c': [0, 0], 'b': [0, 0]})
defaultdict(None, {'a': [0, 0], 'c': [0, 0], 'b': [0, 0]})
0 0
defaultdict(None, {'a': [1, 1], 'c': [1, 1], 'b': [1, 1]})
1 1
defaultdict(None, {'a': [3, 5], 'c': [3, 5], 'b': [3, 5]})
3 5
defaultdict(None, {'a': [6, 11], 'c': [6, 11], 'b': [6, 11]})
Stephen Rauch
  • 47,830
  • 31
  • 106
  • 135
  • `fromkeys` is a trap; don't use it. You've got the same list object as every value. – user2357112 Jun 18 '18 at 01:49
  • Yes thanks, figured it out. They basically point to same object in memory. It just seemed attractive I didn't wanna write a loop, but I guess I'll have to. – jastner109 Jun 19 '18 at 02:03

0 Answers0