将字符串转换为python dict

时间:2015-08-14 19:56:24

标签: python dictionary

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

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

基本上我想从句子中跳过那个“,”并构造一个字典。任何建议都会很棒!提前谢谢!

3 个答案:

答案 0 :(得分:8)

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

import ast
my_dict = ast.literal_eval('{{{0}}}'.format(my_string))

答案 1 :(得分:1)

您也可以在",上拆分并删除空白和"

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

答案 2 :(得分:0)

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