A
A
Art00052020-09-02 20:46:19
Python
Art0005, 2020-09-02 20:46:19

Is it possible to store a storage reference in a dictionary?

I need so that through a certain key I can access the object that is under this key and change the object itself (not the value of the key, the value will remain the same reference to this object). That is, for example, so that dict[1] leads me to a variable and so that I can change the variable itself. Is it possible and how?
I need to have a dictionary key change the content of the value of this key

Answer the question

In order to leave comments, you need to log in

3 answer(s)
P
PavelMos, 2020-09-03
@Art0005

On stackexachange, they suggest doing it through a function - in the dictionary, each variable has its own function in the key value, which simply returns the variable. You will need to access the value in the dictionary with the addition () after

def ret_a():
    return a
a='xxx'
ret_a()
Out[161]: 'xxx'
a='zzz'
ret_a()
Out[163]: 'zzz'
d={'a':ret_a}
d['a']()
Out[164]: 'zzz'
a='bbb'
d['a']()
Out[166]: 'bbb'

If we just make a universal function def f(x): return(x), then it will correctly return the current value of the variable, but the value will not change through the dictionary:
def ret(a):
    return(a)
b=1000
ret(b)
Out[175]: 1000
d2={'a':ret(b)}
d2
Out[180]: {'a': 1000}
b=9999
ret(b)
Out[182]: 9999
d2
Out[183]: {'a': 1000}

S
soremix, 2020-09-02
@SoreMix

You can create your own class and store the value in it, otherwise it will not work like

D
Dr. Bacon, 2020-09-02
@bacon

Well, this is standard behavior, it's not clear what the problem is?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question