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 ‘>

31st Jan 2020, 8:08 AM
Danny Mientjes
Danny Mientjes  - avatar
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)}')
31st Jan 2020, 2:51 PM
Lothar
Lothar - avatar
+ 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
31st Jan 2020, 8:12 AM
✳AsterisK✳
✳AsterisK✳ - avatar
+ 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.
31st Jan 2020, 3:16 PM
Danny Mientjes
Danny Mientjes  - avatar
0
AsterisK, thanks, I will try to solve it with a dictionary.
31st Jan 2020, 10:16 AM
Danny Mientjes
Danny Mientjes  - avatar