0

I have the following situation:

>>> a = 1
>>> d = {"a": a}
>>> d
{'a': 1}
>>> d["a"] = 2
>>> d
{'a': 2}
>>> a
1

Of course this is the desired behaviour. However, when I assign 2 to the key "a" of the dictionary d, I would like to know if I can access the variable a instead of its value to modify the value of the variable a directly, accessing it through the dictionary. I.e. my expected last output would be

>>> a
2

Is there any way of doing this?

2

2 Answers 2

3

I suppose you know the idea of mutable and immutable objects. Immutable objects (str, int, float, etc) are passed by value. That's why your desired behaviour can't work. When you do:

a = 1 
d["a"] = a

you just pass the value of a variable to your dict key 'a'. d['a'] knows nothing about variable a. They just both point to same primitive value in memory.

I don't know your case and why you need this behaviour, but you can try to use mutable object. For example:

class A:
    def __init__(self, a: int):
        self._value = a

    @property
    def value(self) -> int:
        return self._value

    @value.setter
    def value(self, a: int):
        # you can put some additional logic for setting new value
        self._value = a

    def __int__(self) -> int:
        return self._value

And then you can use it in this way:

>>> a = A(1)
>>> d = {"a": a}
>>> d['a'].value
1
>>> d["a"].value = 2
>>> d['a'].value
2
>>> a.value
2
>>> int(a)
2

But it still seems like an overhead and you should rethink whether you really need this behaviour.

Sign up to request clarification or add additional context in comments.

Comments

-1

When you do

>>> a

, you are calling the value of the variable, a that you set on the first line. You have not changed the value of that variable, hence the output of 1. If you did

>>> d["a"]

, your output would be

>>> 2

. If you want this value to be the variable a's value too, set the value of a to the value of d["a"]. Example-

>>> a = 1
>>> d = {"a": a}
>>> d
{'a': 1}
>>> d["a"] = 2
>>> d
{'a': 2}
>>> a = d["a"]
>>> a
2

1 Comment

While this provides the output that OP wants, it does not quite do what OP is trying to achieve

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.