如何使用 python 将 CSV 文件中的值和键分开,然后将其转换为 python 的字典

How to separate values and keys in a CSV file with python that is turned into a dictionary with python

我有一个 csv 数据集,它使用 python 中的 DictReader 打开,我希望将键和值分开。

import csv

with open ('student_marks.txt') as csv_file:
    csv_reader = csv.DictReader(csv_file)
    for keys in csv_reader:
        print(keys)


我有这个输出,我希望将输出中的键和值分开

{'Student ID': '4665178', 'Homework Total (20%)': '95.9', 'Project 1 (10%)': '91.9', 'Midterm (20%)': '91.2', 'Project 2 (10%)': '90.9', 'Final (40%)': '99'}
{'Student ID': '4665187', 'Homework Total (20%)': '83.1', 'Project 1 (10%)': '83', 'Midterm (20%)': '75.7', 'Project 2 (10%)': '92', 'Final (40%)': '78.6'}
{'Student ID': '4665203', 'Homework Total (20%)': '89.9', 'Project 1 (10%)': '73.6', 'Midterm (20%)': '98.9', 'Project 2 (10%)': '84.1', 'Final (40%)': '95.2'}
{'Student ID': '4665219', 'Homework Total (20%)': '81.3', 'Project 1 (10%)': '88.5', 'Midterm (20%)': '84.8', 'Project 2 (10%)': '81.2', 'Final (40%)': '91.1'}

您可以像这样使用built-in方法:

import csv

with open('student_marks.txt') as csv_file:
    csv_reader = csv.DictReader(csv_file)
    for i in csv_reader:
        print(list(i.keys()))
        print(list(i.values()))

i.keys 方法将始终 return 相同 header 或每次迭代中 csv 文件的第一行。