Create Dictionary with name and value of list of variables

38 Views Asked by At

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

1

There are 1 best solutions below

1
sequoia On

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.