+ 4

How can i create a LIST, DICTIONARY and TUPLE with user input?

30th Jul 2019, 3:30 AM
Hari Krishna Sahu
Hari Krishna Sahu - avatar
6 Respostas
+ 6
Lists and tuples can be easily generated from strings depending on how you wish to split them. A primitive example: usr_inp = input() print(list(usr_inp)) print(tuple(usr_inp)) A dictionary is tricker. You can rely on literal_eval https://docs.python.org/3/library/ast.html#ast.literal_eval or just parse it yourself if you can be sure that the input string will always conform to how a dict is represented in Python. https://stackoverflow.com/questions/988228/convert-a-string-representation-of-a-dictionary-to-a-dictionary
30th Jul 2019, 4:01 AM
Hatsy Rei
Hatsy Rei - avatar
+ 5
On SL you can try the following way of getting the user to enter a dictionary in python. out_dct={i.strip():j.strip() for i,j in [tuple(k.split(':')) for k in input().split(',') ]} print(out_dct) Enter text on one line as: a : apple juice, b : banana juice , c : carrot juice https://code.sololearn.com/c6YFNWDMNm06/?ref=app
30th Jul 2019, 5:39 AM
Louis
Louis - avatar
+ 2
One element at a time 🤗
31st Jul 2019, 10:18 AM
Sanjay Kamath
Sanjay Kamath - avatar
+ 1
To show in SL how your code works you can use samples or random data.
30th Jul 2019, 7:00 AM
Sebastian Keßler
Sebastian Keßler - avatar
0
mm not entirely sure what you mean, but you can use the exec function to execute python code based on input and string value (in this example I entered the value of “test” in input to create a list) createlist = input() + " = []" exec(createlist) #I entered “test” as input which created a list named test test.append("hi") print(test) however, I would assume this method should be avoided if at all possible...
30th Jul 2019, 4:50 AM
Jake
Jake - avatar
- 1
Please someone help me. I am a beginner who wants to become a professional web developer and a design as well. What skill do i need and where can i learn it better?
6th Aug 2019, 7:47 AM
Awinpang Ayariga
Awinpang Ayariga - avatar