0

I need to get the variable name instead of the variable value.

I have a situation like this:

Type1 = 1
Type2 = 2

fields = [Type1, Type2]
for field in fields:
   value = field.__name__ #or something like 
   print(value)

Expected result is

Type1 
Type2

Ty for helping

3
  • 4
    It looks like you should have used a dict instead of two variables that are only related by their names... Commented Feb 14, 2021 at 17:24
  • 1
    What result do you expect if both variables have the same value? Commented Feb 14, 2021 at 17:35
  • Doesn't matter. Commented Feb 14, 2021 at 17:37

1 Answer 1

2

Though i don't think there is any way (or i don't know) but an easy way is to store them in a dict like this;

my_dict = {'Type1': 1, 'Type2': 2}

Then to get the variable name, you just need to loop over the my_dict and get all the keys and simply use them as you want.

for key, value in my_dict.items():
    print(key)

this will give an output like this;

Type1
Type2
Sign up to request clarification or add additional context in comments.

2 Comments

Type1 and Type2 are passed from url in django...
I don't think that has any problem with the solution. When you get them, you can first update the my_dict and store them inside it and then apply my solution

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.