One potential way of doing it is like so (see https://stackoverflow.com/a/592891/11530613):
def namestr(obj, namespace):
return [name for name in namespace if namespace[name] is obj]
a,b,c = 1,2,3
list = [a,b,c]
d = {f'{namestr(i, globals())[0]}': i for i in list}
This gives:
{'a': 1, 'b': 2, 'c': 3}
This is definitely a bad idea though, especially with your toy example. For example, integers in Python are the same "object"—if I say:
a = 1
e = 1
a is e
I get True
, even though I'm testing identity and not equality. So the moment I have another variable with the same value from your toy example above, the is
test might evaluate to True, and you could get bad results. Case in point:
def namestr(obj, namespace):
return [name for name in namespace if namespace[name] is obj]
a,b,c = 1,2,3
list = [a,b,c]
__ = 1
d = {f'{namestr(i, globals())[0]}': i for i in list}
yields
{'__': 1, 'b': 2, 'c': 3}
This is simply an explanation of how you could do it, not that you ever should do it this way. But if you had like, a very short notebook or something and you knew no other variables would ever overlap, you might hack it this way.