gpt4 book ai didi

python - 将逗号分隔的 .txt 文件转换为字典

转载 作者:行者123 更新时间:2023-11-28 22:12:14 25 4
gpt4 key购买 nike

我有一个逗号分隔的 .txt 文件,我需要将列表转换为 python 3 中的键:值对:

下面是 .txt 文件:

1988,0.4891
1989,0.2830
1990,0.4312
1991,0.1251
1992,0.0181
1993,0.6182
1994,0.1587
1995,0.1409
1996,0.1505
1997,0.0994
1998,0.1631
1999,0.0330
2000,0.0523
2001,-0.0798
2002,0.1107
2003,0.2308
2004,0.0484
2005,0.0114
2006,0.1088
2007,0.0228
2008,0.1538
2009,0.0038
2010,0.1085
2011,-0.0631
2012,-0.1581
2013,0.2538
2014,0.1377
2015,0.0199
2016,-0.0392
2017,0.0433
2018,-0.0154

这是我的Python代码:

import csv
answer = {}
with open("annual_chesapeakeCapital_diversifiedProgramLV.txt") as infile:
keys = infile.readline().split(",")
values = infile.readline().split("\n")

answer = dict(zip(keys, values))
print(answer)

我做错了什么?

最佳答案

您可以使用csv.reader将行读入两个项目列表的序列中,以便您可以将其传递给字典构造函数来构建您要查找的字典:

with open("annual_chesapeakeCapital_diversifiedProgramLV.txt") as infile:
answer = dict(csv.reader(infile))

关于python - 将逗号分隔的 .txt 文件转换为字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55033054/

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