在逗号

时间:2016-05-07 13:47:37

标签: python string dictionary

我有一个字符串,如下所示

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

可以将所有元素视为键值对。我想从这个字符串构造一个python字典。 有没有直接的方法来做到这一点?

2 个答案:

答案 0 :(得分:3)

如果字符串看起来与您发布的完全相同,则可以用双引号替换单引号,将其括在花括号中并使用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'}

尽管如此,我不确定输入字符串的来源,并且无法保证解决方案可以涵盖您可能拥有的各种输入字符串。

或者,另一个“脏”解决方案是将false替换为False,将true替换为True,用大括号括起来并通过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'}

答案 1 :(得分:0)

这个怎么样:

主要问题是将其转换为字符串

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'}
相关问题