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_
@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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.