+ 2

how to convert a string s1=("ABC:30,BCD:25,Def:35") into dictionary?

6th Jul 2016, 7:43 AM
archana
6 Respuestas
+ 3
If you mean automatically turn strings like those into dictionaries, try parsing them. s1=s1.split (',') //splits the string separated by the comma and gives you a list. To turn the list into a dictionary dict1={} for s in s1: key,value=s.split (':') //splits the letters and number into two variables. value = int (value) //Turn the number string into an integer (optional) dict1[key] = value //Create key and value And you should end up with your dictionary
6th Jul 2016, 9:27 AM
Gershon Fosu
Gershon Fosu - avatar
0
This is the correct answer s1={"ABC":30,"BCD":25,"Def":35}
6th Jul 2016, 7:50 AM
Ajay
0
@ Gershon Fosu I've tried your code but I get the error: AttributeError: 'tuple' object has no attribute 'split'
18th Jul 2016, 6:10 AM
disho
disho - avatar
0
Oops, I forgot to add the argument for the second split. Check now.
18th Jul 2016, 7:50 AM
Gershon Fosu
Gershon Fosu - avatar
0
Parsing should work to change the tuple into a dictionary automatically. But if you simply need to make a very limited number of such changes (e.g. You created a tuple when you meant to create a dictionary), you could simply reassign the Variable: s1=("ABC:30,BCD:25,Def:35") #switching from parentheses (tuple) to \n # curly braces {dictionary}. s1={"ABC:30,BCD:25,Def:35"} #s1 in now a dictionary. print (s1)
13th Nov 2016, 7:50 AM
Lenze
Lenze - avatar
- 1
Why do you need to know this?
8th Jul 2016, 4:50 AM
sophie
sophie - avatar