0

Inputs:

x,y,z = 1,2,3

Expected Output:

some_dict = {'x': 1, 'y': 2, 'z': 3}

Current code:

x,y,z = 1,2,3
some_list = [x,y,z]

some_dict = {}

def convert(some_list):
    for i in some_list:
        some_dict[i.__name__ ] = i    
convert(some_list)

Error:

    some_dict[i.__name__ ]= i
AttributeError: 'int' object has no attribute '__name_
Gооd_Mаn
  • 343
  • 1
  • 16
  • 5
    https://stackoverflow.com/questions/18425225/getting-the-name-of-a-variable-as-a-string/18425523 – ComplicatedPhenomenon Aug 19 '19 at 12:18
  • 1
    Possible duplicate of [Getting the name of a variable as a string](https://stackoverflow.com/questions/18425225/getting-the-name-of-a-variable-as-a-string) – Alex Aug 19 '19 at 12:19
  • First, `[a, b, c, dssds]` is already a list, so `some_list = [a, b, c, dssds]` is sufficient. As you have found out, integer values do not have names. What you are trying to do cannot be done. – Booboo Aug 19 '19 at 12:22

1 Answers1

0

@ComplicatedPhenomenon and @Alex, thank you for pointing to the relevant post, here is the solution to my question:

import inspect

some_dict = {}
x,y,z = 1,2,3
some_list = [x,y,z]

def retrieve_name(var):
    callers_local_vars = inspect.currentframe().f_back.f_locals.items()
    return [var_name for var_name, var_val in callers_local_vars if var_val is var]

for i in some_list:
    some_dict[retrieve_name(i)[0]] = i

print(some_dict)
Gооd_Mаn
  • 343
  • 1
  • 16