gpt4 book ai didi

python - 将 dictreader 转换为字典字典的优雅方法

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

我正在这样做:

headers = ['name', 'accum', 'hi', 'active', 'first', 'last', 'max', 'dirty']
filename = "C:\\Users\\bcrafton\\Desktop\\se0sh0cb0_perf.vec"

with open("C:\\Users\\bcrafton\\Desktop\\se0sh0cb0_perf.vec") as csvfile:

for line in csvfile:
if all(header in line for header in headers):
reader = csv.DictReader(csvfile, fieldnames=headers)
break

效果很好。

但我不想为了使用我的数据而保持文件打开。有没有优雅的方法,将我的数据放入 RAM,而不需要打开文件?

理想情况下,我希望能够关闭文件,然后能够访问我的数据,执行类似的操作

table['name']['address']

最佳答案

尽管您遗漏了一些基本细节,但我还是做了一些假设:

table = {}

with open("C:\\Users\\bcrafton\\Desktop\\se0sh0cb0_perf.vec") as csvfile:
for line in csvfile:
if all(header in line for header in headers):
for row in csv.DictReader(csvfile, fieldnames=headers):
name_row = table.get(row['name'], {})
name_row[row['name']] = row['address']

关于python - 将 dictreader 转换为字典字典的优雅方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39022211/

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