Home > Enterprise >  Assistance needed regarding dictionary syntax in Python
Assistance needed regarding dictionary syntax in Python

Time:07-13

I have a syntax issue while using dictionary for the first time. I hope you guys can help me with it. I'm reading election data from a .csv file. I'm trying to put the names and votes for each candidate into a dictionary so the display would look like this:

Election Results
-------------------------
Total Votes: 369711
-------------------------
Charles Casper Stockham: 23.049% (85213)
Diana DeGette: 73.812% (272892)
Raymon Anthony Doane: 3.139% (11606) 

Here are my codes below. I have already captured the votes for each candidate in each sum variable. I'm just trying to figure out what's the syntax for putting them in the dictionary so they look the display above.

# Import the os module
import os

# Module for reading CSV files
import csv

# Store the file path associated with the file
csvpath = os.path.join('Resources', 'election_data.csv')

# Open the file "read mode" and store contents in the variable
with open(csvpath) as csvfile:

    csvreader = csv.reader(csvfile, delimiter =',')

    print(csvreader)

    csv_header = next(csvreader)

    total_ballots = 0 
    sumCharles = sumDiana = sumRaymon = 0
    candidates = dict()
    candidates_list = ["Charles Casper Stockham","Diana DeGette","Raymon Anthony Doane"]
    candidates["names"] = candidates_list
    votes_list = [sumCharles , sumDiana , sumRaymon]
    candidates["votes"] = votes_list

    for row in csvreader:
        total_ballots = total_ballots   1
        if (row[2] == "Charles Casper Stockham"):
            sumCharles = sumCharles   1
        if (row[2] == "Diana DeGette"):
            sumDiana = sumDiana   1
        if (row[2] == "Raymon Anthony Doane"):
            sumRaymon = sumRaymon   1
    
    print(candidates)
    print(total_ballots)

csvfile

CodePudding user response:

Assuming that the element in position 2 is the name of the candidate and that each line in the csv is a single vote:

# Import the os module
import os

# Module for reading CSV files
import csv

# Store the file path associated with the file
csvpath = os.path.join('Resources', 'election_data.csv')

# Open the file "read mode" and store contents in the variable
with open(csvpath) as csvfile:

    csvreader = csv.reader(csvfile, delimiter =',')

    candidates = dict()
    total_ballots = 0

    for row in csvreader:
    
         total_ballots  = 1
         candidates[row[2]]  = 1


print("Election Results")
print("-"*25)
print("Total Votes:", total_ballots)
print("-"*25)

for candidate, votes in candidates.items():
    percentage = votes / total_ballots * 100
    print("{}: {:.3f}% ({})".format(candidate, percentage, votes)
  • Related