def dict_from_string( data ): d = ''.join(data.split()) d = '{' + d + '}' d = d.replace('=',':') d = d.replace('[',',') d = d.replace(']','') d = d.replace('{,','{') return eval(d) # 'eval' - fais attention!
A part pour un script jetable, c'est une solution plutôt plus à mon goût ... faudrait tester les perfs respectives.
Après, il y a aussi la solution d'écrire un vrai parseur, mais bon, ça devient peut-être un poil overkill !-)
pyparsing -- an object-oriented approach to text processing in Python
http://pyparsing.sourceforge.net/
Stéphane.
Gerard Flanagan wrote:
(snip)
def dict_from_string( data ):
d = ''.join(data.split())
d = '{' + d + '}'
d = d.replace('=',':')
d = d.replace('[',',')
d = d.replace(']','')
d = d.replace('{,','{')
return eval(d) # 'eval' - fais attention!
A part pour un script jetable, c'est une solution plutôt plus à mon goût
... faudrait tester les perfs respectives.
Après, il y a aussi la solution d'écrire un vrai parseur, mais bon, ça
devient peut-être un poil overkill !-)
pyparsing -- an object-oriented approach to text processing in Python
def dict_from_string( data ): d = ''.join(data.split()) d = '{' + d + '}' d = d.replace('=',':') d = d.replace('[',',') d = d.replace(']','') d = d.replace('{,','{') return eval(d) # 'eval' - fais attention!
A part pour un script jetable, c'est une solution plutôt plus à mon goût ... faudrait tester les perfs respectives.
Après, il y a aussi la solution d'écrire un vrai parseur, mais bon, ça devient peut-être un poil overkill !-)
pyparsing -- an object-oriented approach to text processing in Python