How to count the number of letters in a word?

Question:

I’m trying to create a program where if you input a word, it will print out each letter of the word and how many times the letter appears in that word.

Eg; when I input “aaaarggh”, the output should be “a 4 r 1 g 2 h 1”.

def compressed (word):
    count = 0
    index = 0
    while index < len(word):
        letter = word[index]
        for letter in word:
            index = index + 1
            count = count + 1
            print(letter, count)
        break

print("Enter a word:")
word = input()
compressed(word)

So far it just prints out each letter and position in the word.
Any help appreciated, thank you!

(no using dict method)

Asked By: Zahraa

||

Answers:

a="aaaarggh"
d={}
for char in set(a):
    d[char]=a.count(char)
print(d)

output

{'a': 4, 'h': 1, 'r': 1, 'g': 2}
Answered By: mad_

Just type (for Python 2.7+):

import collections
dict(collections.Counter('aaaarggh'))

having:

{'a': 4, 'g': 2, 'h': 1, 'r': 1}
Answered By: enneppi

One way of implementing it using a dict:

def compressed(word):
    letters = dict()
    for c in word:
        letters[c] = letters.get(c, 0) + 1
    for key, value in letters.items():
        print(f'{value}{key}', end=' ')
Answered By: Szabolcs

As others have suggested, you can do this easily with a dict !

test_input = "aaaarggh"

def compressed (word):
  letter_dict = {}
  for letter in test_input:
    if letter not in letter_dict:
      letter_dict[letter] = 1
    else:
      letter_dict[letter] = letter_dict[letter]+1
  return letter_dict

print(compressed(test_input))

Outputs:

{'a': 4, 'r': 1, 'g': 2, 'h': 1}
Answered By: NBlaine

try this, You can use counter it will return dict type

from collections import Counter
print(Counter("aaaarggh"))
Answered By: ashish pal

Counter is concise. But here’s an alternative using defaultdict, which is a subclass of dict.

from collections import defaultdict

test_input = "aaaarggh"

d = defaultdict(int)
for letter in test_input:
    d[letter] += 1

https://docs.python.org/3.6/library/collections.html#defaultdict-examples

Answered By: remykarem
def counter(word):
    
    dic ={}
    for i in [*word]:
        counter = word.count(i)
        d={i:counter}
        dic.update(d)
    return dic

counter("aaaarggh")
Answered By: Lilly
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.