helptaker helptaker - 13 days ago 4
Python Question

How to create variables with their name taken as input from user?

i want to take an input string from user in python3 . for example : abc is an input string . Now i want to create a dictionary insider my program with "abc" name.Is it possible?

Answer

It's very much possible, but I don't recommend trying to do it. If you really need what your asking for, something like this would work:

>>> exec(input("Enter name: ") + ' = {}')
Enter name: myDict
>>> myDict
{}
>>> locals()['myDict']
{}
>>>

However it is generally A bad idea to use exec() especially with a combination of input(). There is usually a better way to do something without it. In fact, there is a better way of doing it.

Instead of trying to create variables based upon user input, use a dictionary instead. This way, you have good control over your "variables". You could easily extend this to add more than one "variable" from user input to your variable dictionary:

>>> varDict = {}
>>> name = input("Enter name: ")
Enter name: myDict
>>> varDict[name] = {}
>>> varDict[name]
{}

You can dynamically create variables using a while loop, and input(). Create a dictionary to hold all your user inputted variables. Create a while loop, then ask the user for a variable name and value:

>>> varDict = {}
>>> while True:
        name = input("Enter a variable name: ")
        value = input("Enter a variable value: ")
        varDict[name] = value


Enter a variable name: var1
Enter a variable value: a
Enter a variable name: var2
Enter a variable value: b
Enter a variable name: var3
Enter a variable value: c
Enter a variable name: 
Traceback (most recent call last):
  File "<pyshell#12>", line 2, in <module>
    name = input("Enter a variable name: ")
KeyboardInterrupt
>>> varDict
{'var1': 'a', 'var2': 'b', 'var3': 'c'}
>>> 
Comments