简体   繁体   中英

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!

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

You can do it via finding tuples using re.findall and passing it to dict

You could have also split on ", and stripped the whitespace and " :

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

A different take using dict comprehension, simpler regex and 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'}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM