+ 2
how to convert a string s1=("ABC:30,BCD:25,Def:35") into dictionary?
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
0
This is the correct answer
s1={"ABC":30,"BCD":25,"Def":35}
0
@ Gershon Fosu I've tried your code but I get the error:
AttributeError: 'tuple' object has no attribute 'split'
0
Oops, I forgot to add the argument for the second split. Check now.
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)
- 1
Why do you need to know this?