gpt4 book ai didi

python - 将多个字典元素追加到列表中

转载 作者:行者123 更新时间:2023-12-01 02:27:23 24 4
gpt4 key购买 nike

我有一个包含多个词典的大列表,我可以通过以下方式访问它:

>>> papers[0]['TI']
"Presence of tau pathology within fetal neural allografts in patients with Huntington's and Parkinson's disease."

我需要访问列表中所有词典的 3 个不同键(['TI']、['AB'] 和 ['MH']),并将它们打印到 .txt 文件,但目前我的代码只打印出所有字典的键之一(['TI'])。这就是我所拥有的:

papers = []   # the list of dictionaries

for each in range(0, len(papers)):
out = []
try:
out.append(str(papers[each]['TI']) + "\n" + str(papers[each]['AB']) + "\n" + str(papers[each]['MH']) + "\n")
except KeyError:
out.append("MISSING INFORMATION \n")

for index, line in enumerate(out):
with open(filename+'_{}.txt'.format(index), 'w') as output:
output.write(line)

注意:我将 str() 添加到每个论文键中,因为我不断收到此错误:

TypeError: cannot concatenate 'str' and 'list' objects

可能出了什么问题,因为我无法打印 3 个不同的 key ,而只能打印一个?任何帮助将不胜感激。

最佳答案

我可能会做这样的事情:

papers = []   # the list of dictionaries
out = []
# ...
# populate your papers list
# ...
for paper in papers:
try:
paper_string = "{TH}\n{AB}\n{MH}\n".format(
TH=paper['TH'],
AB=paper['AB'],
MH=paper['MH'])
except KeyError:
paper_string = "MISSING INFORMATION\n"
finally:
out.append(paper_string)

关于python - 将多个字典元素追加到列表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47241623/

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