Is there a way to call variable value directly, and display that same variable's name instead? | Sololearn: Learn to code for FREE!
Новый курс! Каждый программист должен знать генеративный ИИ!
Попробуйте бесплатный урок
+ 1

Is there a way to call variable value directly, and display that same variable's name instead?

So basically I've been wondering if you can call a variable strictly by its VALUE, and instead, print the variable's NAME. If so, how is this done? For example: obj = "word" print("word") OUTPUT: obj Is something like this possible in Python? If so, what is the most efficient way?

27th Apr 2023, 12:58 PM
Aza
Aza - avatar
6 ответов
+ 10
Suppose you had 2 variables: x = "word" y = "word" Which output would you expect in this case? x or y? Both? Speaking for Python, one could get all local variables as a dictionary and then search values and output the keys.
27th Apr 2023, 1:01 PM
Lisa
Lisa - avatar
+ 8
mi_variable = 42 nombre_variable = [k for k,v in locals().items() if v is mi_variable][0] print(nombre_variable) # salida: 'mi_variable' You can use locals() for getting variable names (as Lisa said)
27th Apr 2023, 1:29 PM
Ugulberto Sánchez
Ugulberto Sánchez - avatar
+ 7
Az_ , >>> the diffuculty in doing like you mentioned is, if you have multiple variables having different names but having the same value. num1 = 7 num2 = 54 num3 = 7 which variable name would you like to get when looking for *7* ? may be this can also help you: obj = 'word' print(f'{obj = }') the output is: obj = 'word' may be you can give us some more details what you wanted to achiev. I have a feeling you only told us half of the story.
27th Apr 2023, 4:48 PM
Lothar
Lothar - avatar
+ 3
Thank you both
27th Apr 2023, 1:58 PM
Aza
Aza - avatar
+ 3
one fairly straightforward option is to store the variables you want to do this with in a key:value paired entity like a dictionary, then you can definitely print both the key and the value. Otherwise, variable names generally don't "really" exist as far as the computer is concerned, so you typically can't do anything with or to them. You'd probably have to separately hardcode the name as a string somewhere (which is essentially what happens with the key:value pairs too, so you may as well just use the existing architecture for it)
28th Apr 2023, 7:28 AM
Orin Cook
Orin Cook - avatar
+ 1
I now realize I should've worded the question better. I went back and edited it
28th Apr 2023, 11:36 AM
Aza
Aza - avatar