0
dictA = {'a':1, 'b':2, 'c':3}
preA = {}
print hex(id(preA))
preB = {}
print hex(id(preB))
dicts = [preA, preB]         #<---- looks like I can't save it like this?

for d in dicts:
    print hex(id(d))
    d = dictA
print preA
print preB

OUTPUT:

0x13348b0
0x13357f0
0x13348b0
0x13357f0
{}
{}

Looks like it has same memory address but when I set preA or preB via the variable 'd' and getting the value back from preA or preB, it's as if they were never set.

Can anyone explain whats going on here?

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
ealeon
  • 12,074
  • 24
  • 92
  • 173
  • 1
    `d = dictA` rebinds `d`. `d` is just a reference, the `for` loop first pointed it to one dictionary, then to another. The list itself doesn't change because you didn't tell the list to change. – Martijn Pieters Jun 10 '15 at 17:02

2 Answers2

1

d is set to the current dictionary at the iteration of each loop. Setting d = dictA is pointless because d will change to the next dictionary as the first step.

vzipp
  • 350
  • 3
  • 8
  • my thinking was that d is the refence to preA so it translate to preA = dictA. What can i do so that d is basically preA? – ealeon Jun 10 '15 at 17:05
  • You can only get `d` to transiently refer to preA, which is its initial state in when entering the body of the loop for the first time. Then it refers to dictA in your assignment `d = dictA`. To get preA = dictA, you will have to make an explicit reference statement. – vzipp Jun 10 '15 at 17:38
1

The issue is, that the thing you are assigning to is not actually the dict object, but the variable named d. If you print hex(id(d)) after the assignment, you should see a different value. In order to actually change the dict value itself, you have to use some function on it that modifies it, e.g. d["a"] = 1, or more relevantly here d.update(dictA).

Snorre
  • 486
  • 3
  • 6