I am trying to count the occurrences of each letter of a word
word = input("Enter a word")
Alphabet=['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
for i in range(0,26):
print(word.count(Alphabet[i]))
This currently outputs the number of times each letter occurs including the ones that don't.
How do I list the letters vertically with the frequency alongside it e.g:
word="Hello"
H 1
E 1
L 2
O 1
easy and simple solution without lib.
here is the link for get() https://docs.quantifiedcode.com/python-anti-patterns/correctness/not_using_get_to_return_a_default_value_from_a_dictionary.html
As @Pythonista said, this is a job for
collections.Counter
:This prints:
If using libraries or built-in functions is to be avoided then the following code may help:
Output:
a 3
b 2
c 1
Try using
Counter
, which will create a dictionary that contains the frequencies of all items in a collection.Otherwise, you could do a condition on your current code to
print
only ifword.count(Alphabet[i])
is greater than 0, though that would slower.