计算用作词典值的List中的项目

时间:2014-11-20 20:18:12

标签: python list dictionary count

我有以下列表工作正常,但最后的打印是borked,我不能让计数器在我的字典中获得多个键时返回每个列表中的正确数量的项目!它应该告诉我有多少人选择了特定的甜点作为他们的最爱。

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]))

期望的输出:

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

但我将所有三个值设置为6!

2 个答案:

答案 0 :(得分:1)

这是一个更简单的版本应该可以正常工作:

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))

请注意更简单的字符串拆分代码,以及如何执行while循环like this意味着您可以避免重复设置代码行。此外,使用defaultdict并迭代dict items()也可以简化代码

答案 1 :(得分:0)

count基于整个sum列表中的desserts,而不是desserts[dessert]

试试这个:

count = len(desserts[dessert])

另请考虑使用defaultdict


让我们退后一步,试试这个:

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]))