typecasting: a string object to a dictionary object
dont bother
dontbotherworld at yahoo.com
Sat Mar 13 00:04:25 EST 2004
Hi,
Thanks! Just one more favour.
I want to sort the entries on this new dictionary.
(Increasing order) and convert it back to a string
where each values are not separated by , but by space.
ie. for example: I have a string s of the form
index: value, index: value, index: value
I converted it to a dictionary by the method you
suggested. I want to sort the entries now, with
increasing order of index.
Once I have the sorted dictionary, I want to convert
it back to a string of the form
1 index:value index:value index:value
Note, that 1 is added because I am creating feature
vectors of the type "spam". index: value pairs are now
separated by space instead of comma and finally I want
to write this to a file.
The whole notion of making a string to a dictionary
was because of sorting.
Can you extend this piece of code for the above
objective. I will indeed be very grateful to you.
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
Thanks
Dont
--- midtoad <stewart at midtoad.homelinux.org> wrote:
> 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
>
> --
> http://mail.python.org/mailman/listinfo/python-list
__________________________________
Do you Yahoo!?
Yahoo! Mail - More reliable, more storage, less spam
http://mail.yahoo.com
More information about the Python-list
mailing list