Assigning numbers to strings in a list {in PYTHON} | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 3

Assigning numbers to strings in a list {in PYTHON}

Please can someone help me on how can I assign numbers to different strings in a list in python eg. Iist = (tube, test, glass, paper, ) I want to assign tube = 1, test = 2 and so on But like in this format assign = (1, 2, 3, 4,) and then use them as strings like : 2+1 = 21 Or 2 + 4 = 24 and get an output as: test tube test paper

15th Jul 2020, 11:10 AM
Nashit Ali Shaikh
Nashit Ali Shaikh - avatar
5 Answers
+ 8
Here a try using enumerate to generate the keys, and a dict comprehension to put all together: def k1(n1, n2): a=("tube","test","glass","paper") c = {k: v for k, v in enumerate(a,1)} return ' '.join([c.get(n1), c.get(n2)]) print(k1(*[1,2]))
15th Jul 2020, 1:22 PM
Lothar
Lothar - avatar
15th Jul 2020, 12:52 PM
Vitaly Sokol
Vitaly Sokol - avatar
+ 5
Kiibo, thanks, additionally suggested another way
15th Jul 2020, 1:06 PM
Vitaly Sokol
Vitaly Sokol - avatar
+ 4
I don't think something like this is possible because you can't use integers as a variable name. But something like this should: a = "tube","test","glass","paper" b = (1,2,3,4) c = dict(zip(b,a)) print(c[2]+c[1]) Output: testtube I modified 𝐊𝐢𝐢𝐛𝐨 𝐆𝐡𝐚𝐲𝐚𝐥 answer a bit for it to work
15th Jul 2020, 11:32 AM
Tomiwa Joseph
Tomiwa Joseph - avatar
+ 2
Thank you everyone for the explanations🙆‍♂️
15th Jul 2020, 12:23 PM
Nashit Ali Shaikh
Nashit Ali Shaikh - avatar