Reputation: 61
I have a csv file with three columns (ID, county, and candidate). There are four candidates and I need to create four lists (one for each candidate). Every time a candidate's name is in the list/column, I want to add that name to a new list and then get the length of that last to see how many votes they received. When I run the script, it sucesfully prints the total number of votes cast, but the length of each candidate list is printing "0" so I dont think they are successfully getting added to the list.
I am fairly new to python. I believe my error is with how I am looping and my if statements.
Thank you.
with open(poll_path, 'r') as csvfile:
csvreader = csv.reader(csvfile, delimiter=',')
#skip the header
next(csvreader,None)
python/
votes = 0
votes = []
candidate_list = 0
candidate_list = []
khan = 'Khan'
khan = []
kahn = 0
correy = "Correy"
correy = []
correy = 0
li = "Li"
li = []
li = 0
otooley = "O'Tooley"
otooley = []
otooley = 0
for row in csvreader:
votes_cast=str(row[0])
votes.append(votes_cast)
candidates=str(row[2])
candidate_list.append(candidates)
if row[2] == str(khan):
khan.append(candidate_list)
if row[2] == str(correy):
correy.append(candidate_list)
if row[2] == str(li):
li.append(candidate_list)
if row[2] == str(otooley):
otooley.append(candidate_list)
total_votes = len(votes)
print("Election Results")
print("----------------------------")
print("Total Votes: " + str(total_votes))
print("----------------------------")
kahn_votes = len(khan)
print(kahn_votes)
correy_votes = len(correy)
print(correy_votes)
li_votes = len(li)
print(li_votes)
otooley_votes = len(otooley)
print(otooley_votes)
Upvotes: 0
Views: 1014
Reputation: 77407
You have many problems with your code. When you assign a variable multiple times as in
khan = 'Khan'
khan = []
kahn = 0
You keep losing the earlier values. kahn
is 0
and the string and list are gone. Those first two lines were pointless.
votes_cast=str(row[0])
The csv
module only creates strings, no need to str
a string.
if row[2] == str(khan):
You know how khan
is 0
? Yeah, this just compares row 2 to the string "0", so i fails. Since khan
was expected to be string in the first place, you shouldn't have cast it either.
There is a much better way to do this using a dictionary to track candidate counts. General notes on the code
open("foo", "r") should be
open("foo")The code
import csv
candidate_count = {}
with open(poll_path, newline=None) as csvfile:
csvreader = csv.reader(csvfile)
for ID, county, candidate in csvreader:
if candidate not in candidate_count:
candidate_count[candidate] = 0
candidate_count[candidate] += 1
# we can sort by total counts to print
for candidate, votes in sorted(candidate_count.items(), key=lambda kv: kv[1]):
print(candidate, votes)
Upvotes: 1