NEWB: how to convert a string to dict (dictionary)

vbgunz vbgunz at gmail.com
Wed May 24 08:37:27 EDT 2006


I am sure something much more elaborate will show it's face but this I
made in about 10 minutes. Didn't do much testing on it but it certainly
does convert your string modeled after a dictionary into a real
dictionary. You might wish to check against more variations and
possibilities and tweak and learn till your heart is content...

def stringDict(stringdictionary):
    ''' alpha! convert a string dictionary to a real dictionary.'''
    x = str(stringdictionary[1:-1].split(':'))
    res = {}
    for index, keyval in enumerate(x.split(',')):
        if index == 0:
            keyval = keyval[2:]
        if index % 2 == 0:
            y = keyval.lstrip(" '").rstrip("'\" ")
            res[y] = None
        else:
            z = keyval.lstrip(" \" '").rstrip("'")
            res[y] = z

    res[y] = z[:-2]
    print res  # {'syllable': "u'cv-i b.v^ y^-f", 'ketiv-qere': 'n',
'wordWTS': "u'8'"}


sd = "{'syllable': u'cv-i b.v^ y^-f', 'ketiv-qere': 'n', 'wordWTS':
u'8'}"
stringDict(sd)

keep in mind the above code will ultimately return every value as a
substring of the main string fed in so may not be very helpful when
trying to save int's or identifiers. None the less, I hope it is useful
to some degree :)




More information about the Python-list mailing list