Abhinav Tripathi
Abhinav Tripathi

Reputation: 178

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?

Upvotes: 0

Views: 682

Answers (2)

fpilee
fpilee

Reputation: 2098

What about this:

The main issue is false being converted to string

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

b = map(lambda x: x.split(":"), a.split(","))
c = map(lambda x: (x[0].replace("\'", "").strip(), x[1].replace("\'", "").strip() ) , b)
d = dict(c)


print(d)


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

Upvotes: 0

alecxe
alecxe

Reputation: 473863

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'}

Upvotes: 3

Related Questions