0

I'd like to know if it's possible to update variables, from a dictionary. In the example, I do not want to set dictionary value to '8', but I'd like to set 'aa' viriable to '8'.

Is it possible?

aa = 1
bb = 2
dct = {'a':aa, 'b':bb}

for k in dct:
    myVar = dct[k] 
    myVar = 8

print aa
print bb

# 1
# 2

1 Answers1

0

Reassigning aa after you have put it in the dct will point that second reference at a new object while the original number remains referenced by the dictionary. So you can not update the value in the dictionary by updating the secondary reference; you must update it with dct['a'] = 8.

If you really want a secondary pointer, you need to store your value in a mutable object, assign both aa and dct['a'] to point at it, and then update that object's data without reassigning aa.

Pavel Komarov
  • 1,153
  • 12
  • 26
  • 1
    NO. Python **never implicitly copies a value**. You can prove this to yourself: `a = 'foo'; d = {}; d['a'] = a; print(d['a'] is a)` – juanpa.arrivillaga Feb 13 '18 at 22:11
  • Well then it must copy the object, because the pointers `aa` and `dct['a']` go different places now. – Pavel Komarov Feb 13 '18 at 22:13
  • _"It appears Python copies the value of `aa` when it puts it in the `dct`"_ - No, it doesn't. @juanpa.arrivillaga is right. The value referred to by `dct['a']` and `aa` is the same object. Try running `id(dct['a']) == id(aa)`. – Christian Dean Feb 13 '18 at 22:14
  • On my system it returns `False`. Using Python 2.7. Edit: Actually it returns `True` until I modify `aa`, after which point it is `False`. So the system decides to make a new primitive and point `aa` at it when you reassign. – Pavel Komarov Feb 13 '18 at 22:15
  • @pvlkmrv No, **Python never implicitely copies an object**. I just proved that to you by using the object-identity operator `is`, but you should read this: https://nedbatchelder.com/text/names.html The semantics of Python variables/assignment simply do not work the way you assume they work – juanpa.arrivillaga Feb 13 '18 at 22:16
  • @pvlkmrv Yeah, changing the value of `aa` will make my code return `False`. `aa` will reference a new object. – Christian Dean Feb 13 '18 at 22:17