abhinavDAIICT abhinavDAIICT - 5 months ago 13
Python Question

Reading comma separated string values as dictionary elements in python

I have a string as below

'type': 'singlechoice', 'add_to_user_messages': false, 'text': 'See you tomorrow', 'next': '31'

All the elements can be treated as key value pairs. I want to construct a python dictionary from this string.
Is there a straight forward method to do this?


If the strings looks exactly like you have posted, you can replace single quotes with double quotes, enclose it in curly braces and load with json.loads():

>>> import json
>>> s = "'type': 'singlechoice',        'add_to_user_messages': false,        'text': 'See you tomorrow',        'next': '31'"
>>> modified_s = '{' + s.replace("'", '"') + '}'                                                            
>>> json.loads(modified_s)
{u'text': u'See you tomorrow', u'type': u'singlechoice', u'add_to_user_messages': False, u'next': u'31'}

Though, I'm not sure where your input string is coming from and cannot guarantee the solution would cover all the variety of input strings you might have.

Or, another "dirty" solution would be to replace false with False, true with True, enclose with curly braces and load via ast.literal_eval():

>>> from ast import literal_eval
>>> modified_s = s.replace("false", "False").replace("true", "True")
>>> modified_s = '{' + s.replace("false", "False").replace("true", "True") + '}'
>>> literal_eval(modified_s)
{'text': 'See you tomorrow', 'type': 'singlechoice', 'add_to_user_messages': False, 'next': '31'}