typecasting: a string object to a dictionary object
midtoad
stewart at midtoad.homelinux.org
Fri Mar 12 23:45:23 EST 2004
dont bother wrote:
> I have a string:
>
> feature_vector. It is of the form
> <index: value, index: value, index: value>
>
> I want to make this string into a dictionary so that I
> can apply .keys() method
okay, here's a solution, assuming that your < and > are part of the string.
If not, remove the line where you take a slice. I'm sure that there are
more Pythonic solutions, but this works...
---
import string
# define a test string
s1 = "<name1: value1, name2: value2, name3: value3>"
# get rid of the < and > by taking a slice
s1 = s1[1:-1]
# split string at the commas
s2 = string.split(s1,',')
mydict = {}
for item in s2:
a,b = string.split(item,":")
mydict[a] = b
print mydict[a]
print "Dictionary is: ", mydict
---
cheers
Stewart
More information about the Python-list
mailing list