Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

Here are some rows of the csv. I have looked over several stackexchange questions, and other resources but have not been able to come up with a clear solution. I converted my csv into a dictionary using DictReader. I am not sure how to turn the specific columns into a tuple key. I also need to filter for the year 2020. I am not sure how to do that without pandas either.

"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"

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Dictionary comprehension is probably the most Pythonic way.

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}

After which data is:

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

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading