+ 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?
6 Respuestas
+ 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.
+ 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)
+ 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.
+ 3
Thank you both
+ 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)
+ 1
I now realize I should've worded the question better. I went back and edited it