将字符串转换为python di

2024-06-26 00:11:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个字符串如下

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

我想从上面的字符串构造一个dict。我尝试了一些建议here

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" }
基本上我想跳过这个句子,然后构造一个DICT。任何建议都很棒!提前谢谢!你知道吗


Tags: ofthetotextworldyourismy
3条回答

您还可以在",上拆分并去除空格和"

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

您的字符串几乎已经是python dict了,所以您可以将它括在大括号中,然后evaluate it这样:

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来实现

相关问题 更多 >