"Number of Contents in Sales Package", "value"=>"Pack of 3"} 像字典一样 {'Number of Conte-6ren">
gpt4 book ai didi

python - 将带有键和值的字符串转换为 python 字典的最有效方法

转载 作者:太空宇宙 更新时间:2023-11-04 07:14:24 24 4
gpt4 key购买 nike

如何转换字符串

{"key"=>"Number of Contents in Sales Package", "value"=>"Pack of 3"}

像字典一样

{'Number of Contents in Sales Package':'Pack of 3'}?

最佳答案

您可以使用 str.replace然后 ast.literal_eval将您的字符串转换为字典,然后重组:

from ast import literal_eval

x = '{"key"=>"Number of Contents in Sales Package", "value"=>"Pack of 3"}'

d = literal_eval(x.replace('=>', ':'))
d = {d['key']: d['value']}

print(d)

{'Number of Contents in Sales Package': 'Pack of 3'}

关于python - 将带有键和值的字符串转换为 python 字典的最有效方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53229554/

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