gpt4 book ai didi

python 字符串列表转换为字典列表

转载 作者:太空宇宙 更新时间:2023-11-03 16:46:37 25 4
gpt4 key购买 nike

我正在尝试转换这样的字符串列表

['{"What is the purpose of a noun?":"To name something or someone."}', '{"What is the purpose of a verb?":"To show action"}']

像这样的字典列表

[{"What is the purpose of a noun?":"To name something or someone."}, {"What       is the purpose of a verb?":"To show action"}]  

这就是txt文件中的原始字符串

{"What is the purpose of a noun?":"To name something or someone."}
{"What is the purpose of a verb?":"To show action in a sentence."}

json 模块不起作用

a = []
with open("proans.txt",'r') as proans:
#transform string in the txt file into list of string by \n
pa = proans.read().split('\n')
#iterate through the list of string, convert string to dict and put them
#into a list
for i in range(len(pa)):
json_acceptable_string = pa[i].replace("\"", "'")
ret_dict = json.loads(json_acceptable_string)
a.append(ret_dict)

我遇到这样的错误

ValueError: Expecting property name: line 1 column 2 (char 1)  

如何将这种类型的字符串列表转换为字典列表?谢谢

最佳答案

删除替换行:json_acceptable_string = ...。无需转义引号。

>>> lst = ['{"What is the purpose of a noun?":"To name something or someone."}', '{"What is the purpose of a verb?":"To show action"}']
>>> import json
>>> [json.loads(el) for el in lst]
[{u'What is the purpose of a noun?': u'To name something or someone.'}, {u'What is the purpose of a verb?': u'To show action'}]
>>> [json.loads(el.replace("\"", "'")) for el in lst]
Traceback (most recent call last):
...
ValueError: Expecting property name: line 1 column 2 (char 1)

与带有 StringIO 对象的原始代码类似的示例:

>>> proans = StringIO.StringIO("""{"What is the purpose of a noun?":"To name something or someone."}
... {"What is the purpose of a verb?":"To show action in a sentence."}""")
>>> pa = proans.read().split('\n')
>>> proans
['{"What is the purpose of a noun?":"To name something or someone."}', '{"What is the purpose of a verb?":"To show action in a sentence."}']
>>> for i in range(len(pa)):
... print json.loads(pa[i])
...
{u'What is the purpose of a noun?': u'To name something or someone.'}
{u'What is the purpose of a verb?': u'To show action in a sentence.'}

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

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