Я не уверен, правильно ли указано название. Я знаю, что это не список, и я пытаюсь перенести результаты в словарь, но это только добавление последнего значения моего l oop.
Так что я вставил весь свой код, но у меня есть вопрос конкретно о моих кандидатах l oop, где я пытаюсь получить проценты голосов за кандидата. Когда я распечатываю информацию, она выглядит следующим образом: введите описание изображения здесь
Как видно на 3-й сессии, результаты показывают кандидатов, а рядом с ними процент и общее количество голосов. , Это то, что я не уверен, что это (не список, не словарь)
Я пытаюсь записать это в моем выводе CSV, однако после стольких способов Я всегда могу написать только последний результат - О'Тули.
Я новичок в этом, поэтому я не уверен, во-первых, почему, даже если я сохраню свой процент в списке после каждого l oop, я все еще сохраняя только процент О'Тули. Вот почему я решил печатать после каждого l oop. Это был мой единственный способ убедиться, что все результаты выглядят так, как на картинке.
import os
import csv
electiondatapath = os.path.join('../..','gt-atl-data-pt-03-2020-u-c', '03-Python', 'Homework', 'PyPoll', 'Resources', 'election_data.csv')
with open (electiondatapath) as csvelectionfile:
csvreader = csv.reader(csvelectionfile, delimiter=',')
# Read the header row first
csv_header = next(csvelectionfile)
#hold number of rows which will be the total votes
num_rows = 0
#total votes per candidate
totalvotesDic = {}
#list to zip and write to csv
results = []
for row in csvreader:
#total number of votes cast
num_rows += 1
# Check if candidate in the dictionary keys, if is not then add the candidate to the dictionary and count it as one, else sum 1 to the votes
if row[2] not in totalvotesDic.keys():
totalvotesDic[row[2]] = 1
else:
totalvotesDic[row[2]] += 1
print("Election Results")
print("-----------------------")
print(f"Total Votes: {(num_rows)}")
print("-----------------------")
#get the percentage of votes and print result next to candidate and total votes
for candidates in totalvotesDic.keys():
#totalvotesDic[candidates].append("{:.2%}".format(totalvotesDic[candidates] / num_rows))
candidates_info = candidates, "{:.2%}".format(totalvotesDic[candidates] / num_rows), "(", totalvotesDic[candidates], ")"
print(candidates, "{:.2%}".format(totalvotesDic[candidates] / num_rows), "(", totalvotesDic[candidates], ")")
#get the winner out of the candidates
winner = max(totalvotesDic, key=totalvotesDic.get)
print("-----------------------")
print(f"Winner: {(winner)}")
print("-----------------------")
#append to the list to zip
results.append("Election Results")
results.append(f"Total Votes: {(num_rows)}")
results.append(candidates_info)
results.append(f"Winner: {(winner)}")
# zip list together
cleaned_csv = zip(results)
# Set variable for output file
output_file = os.path.join("output_Pypoll.csv")
# Open the output file
with open(output_file, "w") as datafile:
writer = csv.writer(datafile)
# Write in zipped rows
writer.writerows(cleaned_csv)