![](/img/trans.png)
[英]What is an elegant way to convert a python dictionary into a comma separated keys string and a comma separated values string?
[英]Reading comma separated string values as dictionary elements in python
我有一個字符串如下
'type': 'singlechoice', 'add_to_user_messages': false, 'text': 'See you tomorrow', 'next': '31'
所有元素都可以視為鍵值對。 我想從此字符串構造一個python字典。 有沒有直接的方法可以做到這一點?
如果字符串看起來完全像您發布的字符串,則可以將單引號替換為雙引號,將其括在花括號中,然后使用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'}
那這個呢:
主要問題是將false轉換為字符串
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'}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.