For example, we have the scores of three courses stored in LIST
.
English, Maths, Physics = 89, 92, 93
LIST = [English, Maths, Physics]
for i in range(len(LIST)):
print(LIST[i])
And I want the print style to be like English, 89
, Maths, 92
, Physics, 93
. Here is a solution that defines another list LIST_name
English, Maths, Physics = 89, 92, 93
LIST = [English, Maths, Physics]
LIST_name = ['English', 'Maths', 'Physics']
for i in range(len(LIST)):
print(LIST_name[i], LIST[i])
I am wondering if there is a built-in function or some other tricks that can help me directly convert English
to "English"
, without defining LIST_name
? And if so, how? As Barmar commented below, what I am looking for is how to go from a value to the name of the variable it came from?
You can have a method that takes variable keyword args as input and gives you dict
with key value pair
def marks(**m):
return m
d=marks(English=90,Maths=100,Physics=90) #call method with keyword args
print(d)
Output :
{'English': 90, 'Maths': 100, 'Physics': 90}
You can also iterate dict
for k,v in d.items():
print(k,v,sep=', ')
Output
English, 90
Maths, 100
Physics, 90