-3
import numpy as np
A = np.array(['B'])
B = 5
C = A[0]

I would like C = 5 if that is possible.

  • you should keep it as dictionary `data = {"B": 5}` and then you can do `data[ A[0] ]` to get `5` – furas May 30 '22 at 02:42
  • 1
    Technically `C = eval(A[0])` would work, but that is an absolutely horrible way of doing it. As furas said, use a `dict` or literally anything else to do whatever it is you're trying to do. – BeRT2me May 30 '22 at 02:45
  • `C= locals()[A[0]]`? – rv.kvetch May 30 '22 at 02:46
  • @BeRT2me The reason I'm using an array is because I'm using 3x3 arrays and changing the values of them but still need the current value of a specific cell. eval seems to work for what im trying to do why would that be bad? Thanks – Jordan Booth May 30 '22 at 02:51
  • [Why is using 'eval' a bad practice?](https://stackoverflow.com/questions/1832940/why-is-using-eval-a-bad-practice), [Why should exec() and eval() be avoided?](https://stackoverflow.com/questions/1933451/why-should-exec-and-eval-be-avoided) – BeRT2me May 30 '22 at 03:00
  • Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking. – Community May 30 '22 at 03:05

2 Answers2

0

An approach like this sounds like it would be far better:

arr = np.array([['A', 'B', 'C'],['D', 'E', 'F'],['G', 'H', 'I']])
values = {'A': 1, 'B': 2, 'C': 3, 'D': 4, 'E': 5, 'F': 6, 'G': 7, 'H': 8, 'I': 9}
print(values['C'])
values['C'] = values[arr[0][1]]
print(values['C'])

Output:

3
2

You can then view the array by values by doing:

np.array(list(map(lambda row: {x:values[x] for x in row}, arr)))

Output:

array([{'A': 1, 'B': 2, 'C': 2}, 
       {'D': 4, 'E': 5, 'F': 6},
       {'G': 7, 'H': 8, 'I': 9}], dtype=object)
BeRT2me
  • 12,699
  • 2
  • 13
  • 31
0
A = ['B']
B = {'B':5}
C = B[A[0]]

When you print C it will give output 5.

Gino Mempin
  • 25,369
  • 29
  • 96
  • 135