0

I have a list of variables in python. And I want to create a dictionary whose key will be the name of the variable and the value will be the content.

a,b,c = 1,2,3
list = [a,b,c]
dic = {f'{item=}'.split('=')[0]:item for item in list}

If I run the previous code, I get as result the following:

{'item': 3}

And i would like to get the following:

{'a':1,'b':2,'c':3}

Thanks in advance

arodrisa
  • 300
  • 4
  • 17
  • 4
    `list = [a,b,c]` is *exactly* the same, in every conceivable respect, as `list = [1,2,3]`. A list contains *values*, nothing is stored concerning where those values came from. – jasonharper Feb 18 '23 at 22:02
  • Related https://stackoverflow.com/questions/1373164/how-do-i-create-variable-variables and https://stackoverflow.com/questions/18425225/getting-the-name-of-a-variable-as-a-string – JonSG Feb 18 '23 at 22:05
  • THanks for your responses, I have already checked those posts, problem is as mentioned in the first comment, that when assigned to a list I loose the identity of the variables. – arodrisa Feb 18 '23 at 22:26

1 Answers1

1

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.

sequoia
  • 143
  • 1
  • 8
  • Thanks for your response. Yes, they may overlap, although is very interesting I cannot use as they will get mixed. – arodrisa Feb 18 '23 at 22:25