typecasting: a string object to a dictionary object
Garry Knight
garryknight at gmx.net
Sat Mar 13 07:40:18 EST 2004
In message <Dlw4c.789400$X%5.393213 at pd7tw2no>, midtoad wrote:
> s2 = string.split(s1,',')
...
> a,b = string.split(item,":")
...
Some further processing will probably be necessary. On my system (Python 2.3
under Mandrake Linux) your code produces the following:
Dictionary is: {' name2': ' value2', ' name3': ' value3', 'name1': '
value1'}
In other words, it leaves extra spaces in all values and in all keys except
'name1'. Putting the following lines after the a,b = string.split(item,":")
will cure that.
a = a.strip()
b = b.strip()
This can be shortened to: a,b = a.strip(),b.strip()
Or, if you're not bothered about doing the 'print mydict[a]' you could
shorten the code by ignoring the above and putting the strip() calls in the
assignment statement:
mydict[a.strip()] = b.strip()
In my opinion, the first method is the best as it makes it very obvious
what's going on.
--
Garry Knight
garryknight at gmx.net ICQ 126351135
Linux registered user 182025
More information about the Python-list
mailing list