Edit: as others have pointed out, you are not really asking for variable names in the right spirit. What you really want is something more like this
order_dict = {"orderA": 3, "orderB": 7, "orderC": 4, "orderD": 2, "orderE": 3}
sorted_list = [(key, order_dict[key]) for key in sorted(order_dict, key=order_dict.get)]
for tup in sorted_list:
print(tup[0], end=" ") # orderD orderA orderE orderC orderB
print('') # ignore, for visuals only
for tup in sorted_list:
print(tup[1], end=" ") # 2 3 3 4 7
print('') # ignore, for visuals only
OP I do not recommend you use the following method, but it still can be achieved, based on this question:
import inspect
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]
orderA = 3
orderB = 7
orderC = 4
orderD = 2
order = [orderA, orderB, orderC, orderD]
order.sort()
# Do this if you don't want `var` to be associated with any order variable
for i in range(len(order)):
print(retrieve_name(order[i]))
# Do this if you don't care
for var in order:
print(retrieve_name(var)[0])
# output: orderD
# orderA
# orderC
# orderB