[Zope] dictionary definition and strings
Jim Washington
jwashin@vt.edu
Thu, 04 Apr 2002 08:21:01 -0500
hans wrote:
>"p.t." wrote:
>
>>If, in a python script, I have a string ="{'aKey':'aValue'}" and I want to
>>generate a dictionary from such a string, what should I do?
>>
>
>in normal python (Products, ExternalMethod), eval( yourstring ) would do.
>in Thru The Web objects (DTML, PythonScript) you cant use eval.
>
Where did the string come from? In most cases you should be able to
return the dictionary rather than its representation string. But if you
really need to, you can use the string functions split and replace to
make the string into a dictionary.
dictAsString ="{'aKey':'aValue'}"
newdict = {}
#remove left brace
newstr = dictAsString.replace('{','')
#remove right brace
newstr = newstr.replace('}','')
#split on commas in case we have multiple items in the dict
splitdict = newstr.split(',')
#go through the splitdict and add the items to the new dict
for anitem in splitdict:
#remove quotes
noquotestr = anitem.replace("'",'')
#now split on colon
splititem = noquotestr.split(':')
#now add to dict
newdict[splititem[0]] = splititem[1]
This is the general idea; you may want to fix cases where the right or
left side may be other than strings.
-- Jim Washington