Reputation: 161
So i just want to print the variable's name. you can see from the case below
Andi = 100
Bill = 50
Kira = 90
List1 = [Andi, Bill, Kira]
for i in List1:
print(i) # Here the problem, i want the Variable Name and Value printed together
So guys i got this code from user, name "Anna Nevison". i wanted to accept her answer, but she delete her post so i post her code here :)
Andi = 100
Bill = 50
Kira = 90
List1 = ['Andi', 'Bill', 'Kira']
for i in List1:
print(i, eval(i))
Upvotes: 1
Views: 4853
Reputation: 475
Maybe these code could help:
Dict_var = dict({"Andi" : 100, 'Bill' : 50, "Kira" : 90})
for i,j in Dict_var.items():
print(i,":",j)
For multiple keys and values:
keys = ['Andi', 'Bill', 'Kira']
values = [100, 50, 90]
Dict_var = dict(zip(keys,values))
for i,j in Dict_var.items():
print(i,":",j)
And the result could be like this:
Andi : 100
Bill : 50
Kira : 90
Upvotes: 0
Reputation: 252
Maybe you should consider using something like a dictionary instead?
people = {
"Andi": 100,
"Bill": 50,
"Kira": 90
}
Then you can access the values associated with the dictionary's key like so:
print(people["Andi"]) # returns 100
Or you can iterate through the dictionary and print all of the values like so:
for person, number in people.items():
print(f'{person}: {number}')
Of course the name 'person' for the variable could be something else... I just didn't know what the numbers in your example are.
Hope that helps!
Upvotes: 2
Reputation: 33335
You can't do this with plain variables. Use a dictionary instead:
mydict = {
'Andi': 100,
'Bill': 50,
'Kira': 25
}
for name in mydict:
print(name, mydict[name])
Upvotes: 5