gpt4 book ai didi

python - 如何读入API输出的多个词典列表?

转载 作者:太空宇宙 更新时间:2023-11-04 02:00:28 26 4
gpt4 key购买 nike

我有一个应用程序以这种格式返回多个字典列表:

 [{'key1':'value1','key2':'value2'}][{'key3':'value3','key4':'value4'}]

如何按原样读取整个字典列表并将列表分开以便在以后的代码中进行进一步分析?

我尝试像这样将数据读入一个变量:

  a = [{'key1':'value1','key2':'value2'}][{'key3':'value3','key4':'value4'}]

但出现错误:

TypeError: list indices must be integers or slices, not dict

最佳答案

处理您创建的字符串的一种粗略方法是执行 string.splitstring.replace,如下所示。

import ast

a = "[{'key1':'value1','key2':'value2'}][{'key3':'value3','key4':'value4'}]"
li = []
#split of ']['
for elem in a.split(']['):
#Replace elements in dictionary to make the string json compliant
d = elem.strip('[]')
#Use literal_eval to convert to dictionary
dct = ast.literal_eval(d)
#Append parsed dictionary to a list
li.append(dct)

print(li)
#[{'key1': 'value1', 'key2': 'value2'}, {'key3': 'value3', 'key4': 'value4'}]

关于python - 如何读入API输出的多个词典列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55815375/

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