0
How to get the variable name when itering
Hi, can anyone help me with this : a="text" b=2 c=1.1 d=(1,2,3) e=[1,2,3] f={1,2,3,4} g={1:4,3:7,4:0,8:a} for i in [a,b,c,d,e,f,g]: print(i,"-->",type(i)) i actually want to print the variable name, not the value so, instead of: text —> <class ‘string ‘> I want to get : a —> <class ‘string ‘>
4 odpowiedzi
+ 4
Danny Mientjes, i can share with you a code that i did some weeks ago to demonstrate handling with dicts. I only filled the dict with your values. I am not sure if this is what you wanted:
dic = {'a': 'text', 'b': 2, 'c': 1.1, 'd': (1,2,3), 'e': [1,2,3], 'f': {1,2,3,4}, 'g': {1:4,3:7,4:0,8:'a'}}
for key, val in dic.items():
print(key, val)
print()
for key, val in dic.items():
print(f'{key} --> {type(val)}')
+ 3
i saw a work around for this in C long time ago, but it not something i need or want to use because it was just like making something tricky, if you need something like that the language have given you dictionary to tangle with
+ 1
Lothar, thanks, I appreciate it.
I like the code you wrote.
But I thought there was an easy way to get the iterations numbers, not the value.
0
AsterisK, thanks, I will try to solve it with a dictionary.