简体   繁体   中英

Python: modify variable stored as a value in a dictionary

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. Ie my expected last output would be

>>> a
2

Is there any way of doing this?

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM