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!

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

Need Your Help

How to check if current date time is within weekend period

php datetime

I'm trying to create some kind of restaurant system that shows a different menu when it's the weekends.

When will “OnReconnected” occur?

signalr signalr-hub

If "OnConnected" is raised when the 1st time we connect to our website, when will "OnReconnected" happen?

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.