Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert strings into python dict

I have a string which is as follows

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

I want to construct a dict from the above string. I tried something as suggested here

split_text = my_string.split(",")
for i in split_text :
    print i

then I got output as shown below:

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

I want output as key pair values of a dictionary as given below :

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

Basically I want to skip that "," from the sentence and construct a dict. Any suggestions would be great! Thanks in advance!

like image 826
d-coder Avatar asked Dec 20 '22 01:12

d-coder


1 Answers

Your string is almost already a python dict, so you could just enclose it in braces and then evaluate it as such:

import ast
my_dict = ast.literal_eval('{{{0}}}'.format(my_string))
like image 77
tzaman Avatar answered Dec 26 '22 10:12

tzaman