将字符串转换为python dict

d-c*_*der 4 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"'
Run Code Online (Sandbox Code Playgroud)

我想从上面的字符串构造一个字典.我尝试了这里建议的东西

split_text = my_string.split(",")
for i in split_text :
    print i
Run Code Online (Sandbox Code Playgroud)

然后我输出如下所示:

"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"
Run Code Online (Sandbox Code Playgroud)

我希望输出作为字典的键对值,如下所示:

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" }
Run Code Online (Sandbox Code Playgroud)

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

tza*_*man 8

你的字符串几乎已经是一个python dict,所以你可以将它括在括号中,然后评估它:

import ast
my_dict = ast.literal_eval('{{{0}}}'.format(my_string))
Run Code Online (Sandbox Code Playgroud)

  • @d-coder`ast.literal_eval`只是解析字符串并返回它,如果它的计算结果为文字.它实际上并不执行它,所以它不容易受到注入攻击. (2认同)