My objective is to convert a list to a dictionary with the keys being the variable name of the list and the index value of the list attached to each key. It needs to be generically viable in the form of a function (since I have many lists that need to be converted to key-value pairs). For example, say I have these two lists:
action = [1, 3, 5, 7, 9]
result = [2, 6, 10, 14, 18]
and I have a function:
def list_to_dict(lst):
...
return dict
The output should be something like this:
action_dict = list_to_dict(action)
result_dict = list_to_dict(result)
print(action_dict)
print(result_dict)
>>> {'action_0': 1, 'action_1': 3, 'action_2': 5, 'action_3': 7, 'action_4': 9}
>>> {'result_0': 2, 'result_1': 6, 'result_2': 10, 'result_3': 14, 'result_4': 18}
So far, all I am able to do for the function is enumerate a list and have the index be the key to the respective values.
def list_to_dict(lst):
dict = {k:v for k, v in enumerate(lst)}
return dict
>>> {0: 1, 1: 3, 2: 5, 3: 7, 4: 9}
However, I am unable to find a way to have the variable name be in the key as a string. I tried var.__name__
but I think that is limited to functions.
CodePudding user response:
Using retrieve_name
by juan Isaza from Getting the name of a variable as a string
import inspect
action = [1, 3, 5, 7, 9]
result = [2, 6, 10, 14, 18]
def retrieve_name(var):
"""
Gets the name of var. Does it from the out most frame inner-wards.
:param var: variable to get name from.
:return: string
"""
for fi in reversed(inspect.stack()):
names = [var_name for var_name, var_val in fi.frame.f_locals.items() if var_val is var]
if len(names) > 0:
return names[0]
def list_to_dict(lst):
name = retrieve_name(lst)
return {f"{name}_{k}":v for k, v in enumerate(lst)}
action_dict = list_to_dict(action)
result_dict = list_to_dict(result)
print(action_dict)
print(result_dict)
Output:
{'action_0': 1, 'action_1': 3, 'action_2': 5, 'action_3': 7, 'action_4': 9}
{'result_0': 2, 'result_1': 6, 'result_2': 10, 'result_3': 14, 'result_4': 18}
CodePudding user response:
you can use zip as below
dic = {k:v for k,v in zip(action,result)}