0

Is it possible to reassign the value referenced to by a variable, rather than the variable itself?

a = {"example": "foo"}
b = a

When I reassign a, it is reassigning the variable a to reference a new value. Therefore, b does not point to the new value.

a = {"example": "bar"}
print(b["example"]) # -> "foo"

How do I instead reassign the value referenced by a? Something like:

*a = {"example": "bar"}
print(b["example"]) # -> "bar"

I can understand if this isn't possible, as Python would need a double pointer under the hood.


EDIT Most importantly, I need this for reassigning an object value, similar to JavaScript's Object.assign function. I assume Python will have double pointers for objects. I can wrap other values in an object if necessary.

David Callanan
  • 5,601
  • 7
  • 63
  • 105

2 Answers2

2

Python variables simply do not operate this way, and simple assignment won't do what you want. Instead, you can clear the existing dict and update it in-place.

>>> a = dict(example="foo")
>>> b = a
>>> a.clear()
>>> a
{}
>>> a.update({'example': 'bar'})
>>> b
{'example': 'bar'}
chepner
  • 497,756
  • 71
  • 530
  • 681
1

You are creating 2 dictionaries, so that's 2 different objects in memory. If you don't want that, keep 1 dictionary only.

a = {"example": "foo"}
b = a
a["example"] = "bar"
print(b["example"])
Thomas Weller
  • 55,411
  • 20
  • 125
  • 222
  • However, I am given another dict from another function, and need to transfer that into my existing dictionary. `update` is what I was looking for in @chepner's answer – David Callanan Jan 22 '20 at 21:15