1

This is from the grok learning website for favorite dessert. I am not sure how to get it to add how many of the votes occured.

votes = {}
msg = input("Name:vote ")
while msg:
  name, vote = msg.split(":")
  if vote not in votes:
    votes[vote] = [name]
  else:
    votes[vote].append(name)
  msg = input("Name:vote ")
for vote in votes:
  print(vote, vote.count(votes), "vote(s):", ' '.join(votes[vote]))

This is the expected outcome:

Name:vote Greg:chocolate
Name:vote Teena:macaroons
Name:vote Georgina:apple pie
Name:vote Will:chocolate
Name:vote Sophia:gelato
Name:vote Sam:ice cream
Name:vote James:chocolate
Name:vote Kirsten:gelato
Name:vote 
apple pie 1 vote(s): Georgina
gelato 2 vote(s): Sophia Kirsten
chocolate 3 vote(s): Greg Will James
macaroons 1 vote(s): Teena
ice cream 1 vote(s): Sam
furas
  • 134,197
  • 12
  • 106
  • 148
R white
  • 21
  • 1
  • at start set `count_votes = 0` and inside `while` loop you can do `count_votes += 1` – furas Jul 28 '19 at 22:29
  • or at start set `count_votes = 0` and inside `for` loop use `count_votes += vote.count(votes)` – furas Jul 28 '19 at 22:30

2 Answers2

1

Why don't you try printing the length of each list.

votes = {}
msg = input("Name:vote ")
while msg:
  name, vote = msg.split(":")
  if vote not in votes:
    votes[vote] = [name]
  else:
    votes[vote].append(name)
  msg = input("Name:vote ")
for vote in votes:
  print(vote, len(votes[vote]), "vote(s):", ' '.join(votes[vote]))
murphy1310
  • 647
  • 1
  • 6
  • 13
0

The vote.count(votes) is giving you the trouble. You can use len() for that.

More importantly, I think your code would be easier to understand if you use both key and value in your loop:

for food, voters in votes.items(): 
  print(food, len(voters), 'vote(s): ', ' '.join(voters))
Sinan Kurmus
  • 585
  • 3
  • 11