-1

So let's say we have the lists a = [1,2,3,4] and s = ["q", "w", "e", "r"]. I want to dedicate every element in s a value in a, so that print(w) prints 2 and so on. You could write

for u in range(0, len(a)):
   s[u] = a[u]

But here print(w) makes no sense and we get an error.

cs95
  • 379,657
  • 97
  • 704
  • 746

2 Answers2

2

A dict does exactly this:

In [1261]: d = dict(zip(s, a))

In [1262]: d
Out[1262]: {'e': 3, 'q': 1, 'r': 4, 'w': 2}

To get the value associated with e, simply use dict indexing:

In [1263]: d['e']
Out[1263]: 3
cs95
  • 379,657
  • 97
  • 704
  • 746
1

The following solution does exactly what you have specified, using the built-in exec() function. However, you should never ever ever use it! It is hideously unsafe, and I am only posting it for completeness' sake. Use the solution after it instead.

for i in range(len(s)):
    exec(s[i] + "=" + str(a[i]))

What you should do is use a dictionary:

myDictionary = dict(zip(s, a))

What this does is it matches each element of the lists s and a into key-value pairs in a dictionary by their index (meaning that they are matched based on their order).

And then you can do:

>>> print(myDictionary["w"])
2
stelioslogothetis
  • 9,371
  • 3
  • 28
  • 53