Python formatting and value output.

Hello! Having trouble with my python code. Two issues-
One- How can I format this nicely, so that the values of the dictionary line up under the header? I was able to get all the keys to print on separate lines but that's it.
Two- my loop that is supposed to give me the candidate with the most votes keeps pulling in the candidate with the highest key (the last input). Thanks in advance for any help!
Here is an example of the output I want
ID Name    Votes   %of Votes
1   Homer   90          90%
2   Dan        10         10%
and the winner is Dan!

dct = {}
i = 1
    name = input('Please enter a name: ')
    if name == '':

    votes = input('Please enter vote total for canidate: ')
    totalVotesInt= map(int, totalVotes)
    total = sum(totalVotesInt)
    dct[i] = list((name,int(votes)))   
    i += 1

maxVal = 0
for i in range(1, len(dct) + 1):
    if dct[i][1] > maxVal:
        maxInd = i
    dct[i].append(int((dct[i][len(dct[i]) - 1]) / total * 100))

header='{:>0}{:>10}{:>10}{:>20}'.format('ID','Name','Votes','% of Total Vote')
print1=("\n".join("{}\t{}".format(key, value) for key, value in dct.items()))
print('Total '+str(total))
print('The Winner of the Election is '+ dct[maxInd][0])

Open in new window

L WardAsked:
Who is Participating?
gelonidaConnect With a Mentor Commented:
The two issues were:

Formatting issue:
you did not use formatting strings for displaying the lines except of for the header line.

I used an explicit for loop instead of a list expression and a join, but can rewrite it with list expressions and join if you want to.

problem with determining the max value:
 you forgot to update the value of maxVal in the if statement

Here a  slightly rewritten version, that works for python2 and for python3

from __future__ import print_function

dct = {
    1: [ "Homer", 90 ],
    2: [ "Dan", 10 ],

total = 100

# calculate percentages and determine max index
max_key = 0 # this line is not really needed
maxVal = 0
for key, value in  dct.items():
    if value[1] > maxVal:
        max_key = key
        maxVal = value[1]
    value.append(int(value[-1] * 100 / total))

fmt_str = '{:>2} {:<10}{:>8} {:>10}'
header=fmt_str.format('ID','Name','Votes','% of Total Vote')
for key, value in  dct.items():
    print(fmt_str.format(key, *value))

print('Total', total)
print('The Winner of the Election is', dct[max_key][0])

Open in new window

should give following output:
ID Name         Votes % of Total Vote
 1 Homer           90         90
 2 Dan             10         10
Total 100
The Winner of the Election is Homer

Open in new window

L WardAuthor Commented:
Thank you, you're a life saver!
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.