gpt4 book ai didi

python - 将字符串转换为 python 字典

转载 作者:太空狗 更新时间:2023-10-30 01:54:02 24 4
gpt4 key购买 nike

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

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

我想从上面的字符串构造一个字典。我尝试了一些建议 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" }

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

最佳答案

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

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

关于python - 将字符串转换为 python 字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32017755/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com