[英]How do I make a dictionary with keys from a other dictionary and values from a csv file in 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)
我有這個 output 我希望在輸出中分離鍵和值
{'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'}
您可以像這樣使用內置方法:
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
方法將在每次迭代中始終返回相同的 header 或 csv 文件的第一行。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.