0

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?

sopho-saksham
  • 171
  • 1
  • 11

1 Answers1

0

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'}
>>> 
Community
  • 1
  • 1
Christian Dean
  • 22,138
  • 7
  • 54
  • 87
  • thanks for your help. Actually , i have to create a compiler like program in python for college assignment for which we have not been taught anything in the lecture. So to easily implement a struct like feature , i was trying if this dynamic naming is possible , so that my work could get a little bit easier. Can you suggest any less complex method to implement a structure like feature. Any help will be greatly appreciated. – sopho-saksham Nov 11 '16 at 15:51
  • Also , i was thinking that even if i create a dictionary with input name then how i would be able to access the dictionary in my further program – sopho-saksham Nov 11 '16 at 15:55
  • @helptaker The closes your gonna get to seamless dynamic naming is using a dictionary. And really, this isn't to complex of a method. I'll add some more to my answer to help clear your confusion though. – Christian Dean Nov 11 '16 at 16:00
  • @helptaker Your welcome. And see if what I've added to my answer helps. – Christian Dean Nov 11 '16 at 16:13