需要从 csv 中创建元组作为字典键,格式为 (year, state_po, candidate) = candidatevotes without pandas

Need to create tuples as dictionary keys from a csv in the form (year, state_po, candidate) = candidatevotes without pandas

这是 csv 的一些行。我查看了几个 stackexchange 问题和其他资源,但未能提出明确的解决方案。我使用 DictReader 将我的 csv 转换成字典。我不确定如何将特定列变成元组键。我还需要过滤 2020 年。如果没有 pandas,我也不知道该怎么做。

"year","state","state_po","county_name","county_fips","office","candidate","party","candidatevotes","totalvotes","version","mode"
2000,"ALABAMA","AL","AUTAUGA","1001","PRESIDENT","AL GORE","DEMOCRAT",4942,17208,20191203,"TOTAL"
2000,"ALABAMA","AL","AUTAUGA","1001","PRESIDENT","GEORGE W. BUSH","REPUBLICAN",11993,17208,20191203,"TOTAL"
2000,"ALABAMA","AL","AUTAUGA","1001","PRESIDENT","RALPH NADER","GREEN",160,17208,20191203,"TOTAL"

字典理解可能是最 Pythonic 的方式。

import csv
with open('csv') as file:
    reader = csv.DictReader(file)
    data = {(i['year'], i['state_po'], i['candidate']): i['candidatevotes'] for i in reader}

之后data是:

{('2000', 'AL', 'AL GORE'): '4942',
 ('2000', 'AL', 'GEORGE W. BUSH'): '11993',
 ('2000', 'AL', 'RALPH NADER'): '160'}