![](/img/trans.png)
[英]How to convert Python dict to JSON when some keys are not strings?
[英]convert strings into python dict
我有一个字符串,如下所示
my_string = '"sender" : "md-dgenie", "text" : "your dudegenie code is 6326. welcome to the world of dudegenie! your wish, my command!", "time" : "1439155575925", "name" : "John"'
split_text = my_string.split(",")
for i in split_text :
print i
然后我输出如下所示:
"sender" : "md-dgenie"
"text" : "your dudegenie code is 6632. welcome to the world of dudegenie! your wish
my command!" ### finds "," here and splits it here too.
"time" : "1439155803426"
"name" : "p"
我希望输出作为字典的键对值,如下所示:
my_dict = { "sender" : "md-dgenie",
"text" : "your dudegenie code is 6632. welcome to the world of dudegenie! your wish, my command!",
"time" : "1439155803426",
"name" : "p" }
基本上我想从句子中跳过那个“,”并构造一个字典。 任何建议都会很棒! 提前致谢!
你的字符串几乎已经是一个python dict,所以你可以将它括在括号中,然后评估它 :
import ast
my_dict = ast.literal_eval('{{{0}}}'.format(my_string))
my_string =' "sender" : "md-dgenie", "text" : "your dudegenie code is 6326. welcome to the world of dudegenie! your wish, my command!", "time" : "1439155575925", "name" : "John"'
import re
print dict(re.findall(r'"([^"]*)"\s*:\s*"([^"]*)"',my_string))
您可以通过使用re.findall
查找tuples
并将其传递给dict
你也可以拆分",
并删除空格和"
:
my_string = '"sender" : "md-dgenie", "text" : "your dudegenie code is 6326. welcome to the world of dudegenie! your wish, my command!", "time" : "1439155575925", "name" : "John"'
print(dict(map(lambda x:x.strip('" ') ,s.split(":")) for s in my_string.split('",')))
{'name': 'John', 'time': '1439155575925', 'sender': 'md-dgenie', 'text': 'your dudegenie code is 6326. welcome to the world of dudegenie! your wish, my command!'}
使用dict理解,更简单的正则表达式和zip(*[iter()]*n)
的另一种看法:
import re
my_string = '"sender" : "md-dgenie", "text" : "your dudegenie code is 6326. welcome to the world of dudegenie! your wish, my command!", "time" : "1439155575925", "name" : "John"'
{k:v for k,v in zip(*[iter(re.findall(r'"(.+?)"',my_string))]*2)}
{'text': 'your dudegenie code is 6326. welcome to the world of dudegenie! your wish, my command!', 'sender': 'md-dgenie', 'name': 'John', 'time': '1439155575925'}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.