Home > front end >  Dictionary task in Python: Elections
Dictionary task in Python: Elections

Time:03-06

The first line gives the number of entries. Further, each entry contains the name of the candidate and the number of votes cast for him in one of the states. Summarize the results of the elections: for each candidate, determine the number of votes cast for him. Use dictionaries to complete the tasks.

Input: Number of voting records (integer number), then pairs <> - <>

Output: Print the solution of the problem.

Example:

Input:

5
McCain 10
McCain 5
Obama 9
Obama 8
McCain 1

Output:

McCain 16
Obama 17

My problem is at the step when I have to sum keys with same names but different values.

My code is:

cand_n = int(input()) 
count = 0 
countd = 0 
cand_list = [] 
cand_f = [] 
num = [] 
surname = [] 
edict = {} 
while count < cand_n: 
    cand = input() 
    count  = 1 
    cand_f = cand.split(' ') 
    cand_list.append(cand_f) 
for k in cand_list: 
    for i in k: 
        if i.isdigit(): 
            num.append(int(i)) 
        else: surname.append(i) 
while countd < cand_n: 
    edict[surname[countd]] = num[countd] 
    countd  = 1 
print(edict)

CodePudding user response:

You can add the name and vote to the dictionary directly instead of using one more for() and while(). If the name does not exist in the dictionary, you add the name and vote. If the name exists in the dictionary, increase the vote.

cand_n = int(input())
count = 0
cand_list = []
cand_f = []
edict = {}
while count < cand_n:
    cand = input()
    count  = 1
    cand_f = cand.split(' ')
    if cand_f[0] in edict:
        edict[cand_f[0]]  = int(cand_f[1])
    else:
        edict[cand_f[0]] = int(cand_f[1])
print(edict)
  • Related