Mathmos
Mathmos

Reputation: 151

Counting items in a List used as a Dictionary Value

I have the following dictionary of lists working fine, but the printing at the end is borked, I can't get the counter to return correct numbers of items in each list as soon as I get more than one key in my dictionary! It's supposed to tell me how many people have chosen a particular dessert as their favourite.

desserts = {}

name_vote = input ('Name:vote ')

while name_vote != '':
  no_colon_name_vote = name_vote.replace(":", " ")
  listed_name_vote = no_colon_name_vote.split()
  name = listed_name_vote[0] 
  vote = ' '.join(listed_name_vote[1:])
  if vote not in desserts:
    desserts[vote] = [name]
  else:
    desserts[vote].append(name)
  name_vote = input ('Name:vote ')

for dessert in desserts:
  count = sum(len(entries) for entries in desserts.values())
  print(dessert, count,'vote(s):',' '.join(desserts[dessert]))

Desired output:

apple pie 1 vote(s): Georgina
gelato 2 vote(s): Sophia Kirsten
chocolate 3 vote(s): Greg Will James

But instead I get all three values set to 6!

Upvotes: 1

Views: 210

Answers (2)

Anentropic
Anentropic

Reputation: 33923

Here's a simpler version which should work ok:

from collections import defaultdict

desserts = defaultdict(list)

while True:
    name_vote = input('Name:vote ')
    if name_vote == '':
        break
    name, vote = name_vote.split(':')
    desserts[vote].append(name)

for dessert, names in desserts.items():
    print(dessert, len(names), 'vote(s):', ' '.join(names))

Note the simpler string splitting code, and also how doing the while loop like this means you can avoid having to repeat the line of setup code. Also, using a defaultdict and iterating over the dict items() also simplify the code a bit

Upvotes: 0

Brian Cain
Brian Cain

Reputation: 14619

count is based on the sum over the entire desserts list, not desserts[dessert].

Try this:

count = len(desserts[dessert])

Also consider using defaultdict.


Let's take a step back and try this instead:

desserts = collections.defaultdict(list)
while name_vote != '':
    name_vote = input('Name:vote ')
    if not name_vote:
        break
    name, vote = no_colon_name_vote.split(':')
    desserts[vote].append(name)

for dessert in desserts:
    count = len(desserts[dessert])
    print(dessert, count,'vote(s):',' '.join(desserts[dessert]))

Upvotes: 0

Related Questions