1

On my recent project I am facing with new obstruction where I need to declare a variable based on value of another string.

What I need:

'Hai'= 2

The String Hai is initialized at variable x,

x='hai' then I need 'hai'= 2

Now all I want is the value of x to point to a int (different int for different values of x).

So if,

x='bye'

then,

'bye'=20
Shivam Jha
  • 3,160
  • 3
  • 22
  • 36

3 Answers3

0

As mentioned in the comments, you are describing a dictionary:

A dictionary provides a mapping between two different values (also known as an associative array in other languages). You can declare one in Python like this:

mydict = {"hai": 2, "bye": 20}

print(mydict["hai"])
# 2

print(mydict["bye"])
# 20

You can then use variables as the key to access the dictionary:

mykey = "bye"

print(mydict[mykey])
# 20

For more details, please see the Python docs for dictionaries

captainGeech
  • 302
  • 1
  • 5
  • 17
0

You need to get a dictionary as @Saadat said:

x = {'hai': 2, 'bye': 20}

Now

x['hai']

Will give 2 and the other key will give 20 Or:

y='hai'
z = x[y] #z=2

Also another worse approach:

if x == 'hai':
  hai = 2
elif x == 'bye'
  bye = 20

...
Wasif
  • 14,755
  • 3
  • 14
  • 34
0

If you don't go with dictionary and need to declare a variable name & value at runtime. We can achieve this with setattr()

Try this,

class Sample:
   pass

obj = Sample()
x = 'hai'
setattr(obj, x, 20)
print(obj.hai)
Maran Sowthri
  • 829
  • 6
  • 14