将dictreader转换为字典字典的优雅方式

时间:2016-08-18 15:33:05

标签: python dictionary file-io

我这样做:

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']

1 个答案:

答案 0 :(得分:1)

即使您遗漏了一些重要细节,我仍然做了一些假设,结果如下:

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']