You can use collections.Counter
to do this easily:
from collections import Counter
words = []
input_word = True
while input_word:
input_word = raw_input()
words.append(input_word)
counted = Counter(words)
for word, freq in counted.items():
print word + " - " + str(freq)
Note that an empty string evaluates to false, so rather than breaking when it equals an empty string, we can just use the string as our loop condition.
Edit: If you don't wish to use Counter
as an academic exercise, then the next best option is a collections.defaultdict
:
from collections import defaultdict
words = defaultdict(int)
input_word = True
while input_word:
input_word = raw_input()
if input_word:
words[input_word] += 1
for word, freq in words.items():
print word + " - " + str(freq)
The defaultdict
ensures all keys will point to a value of 0
if they havn't been used before. This makes it easy for us to count using one.
If you still want to keep your list of words as well, then you would need to do that in addition. E.g:
words = []
words_count = defaultdict(int)
input_word = True
while input_word:
input_word = raw_input()
if input_word:
words.append(input_word)
words_count[input_word] += 1