I have a variable fruit = 13
, when I print(fruit)
I get 13
.
How do I print out the variable name so I get 'fruit'
to print out? I don't want to have to use print('fruit')
because I will be using functions.
I have a variable fruit = 13
, when I print(fruit)
I get 13
.
How do I print out the variable name so I get 'fruit'
to print out? I don't want to have to use print('fruit')
because I will be using functions.
What you're looking for is a dictionary.
food = {'fruit':13, 'vegetable':15}
for item in food:
print(item, food[item])
Result:
fruit 13
vegetable 15
Just print
the next
key in the locals
dictionary with the desired value. Below 13 is the value:
print next(k for k, v in locals().items() if v == 13) # get variable that is equal to 13
You could achieve a similar behaviour by using a dictionary and a for
-loop iterating through it:
#!/usr/bin/env python3
# coding: utf-8
# define a dict with sample data
d = {'fruit': 13}
# print keys and values of sample dict
for key, val in d.items():
print(key, val)
Output looks like:
fruit 13
you could just do this.
print [n for n in globals() if globals()[n] is fruit][0]
>>> fruit = 13
>>> n = None
>>> print [n for n in globals() if globals()[n] is fruit][0]
fruit
>>> b = None
>>> b = [n for n in globals() if globals()[n] is fruit][0]
>>> b
'fruit'
>>> type(b)
<type 'str'>
>>>
you can also make an object off of a variable in your namespace like this if you'd like
b = {globals()[n]: n for n in globals() if globals()[n] is fruit}
which you can then go and get the name text out by the value of that object
print b[fruit]
output:
>>> b = {globals()[n]: n for n in globals() if globals()[n] is fruit}
>>> b
{13: 'fruit'}
>>> fruit
13
>>> b[fruit]
'fruit'
While there are ways to do this, (personally I think a dictionary is what you want) I'd like to explain why many people are balking at it, since on the face of it, it seems like a pretty reasonable task.
But there's a reason this is so difficult in Python (and most other languages I can think of). The reason is that, most of the time, one can think of a variable name as shorthand for a real, underlying meaning which is in your head. Most languages are designed with the idea that changing the shorthand should not change the output of the code.
Suppose you have code like this:
fruit = 10
print('Amount of fruit', fruit)
There are a million names we could have chosen for fruit
-- fruit_quantity
, num_fruits
, etc. but one underlying concept that variable represents, which is: amount of fruit. So if you want a label for the number, use the name of the underlying concept.