-1

How do I create a function that will let me input a word, and it will execute to create a dictionary that counts individual letters in the code. I would want it to display as a dictionary, for example, by inputting 'hello' it will display {'e': 1, 'h': 1, 'l': 2, 'o': 1}

I AM ALSO required to have 2 arguments in the function, one for the string and one for the dictionary. THIS IS DIFFERENT to the "Counting each letter's frequency in a string" question.

For example, I think I would have to start as,

d = {}
def count(text, d ={}):

    count = 0
    for l in text:
      if l in d:
        count +=1
      else: 
        d.append(l)

    return count

But this is incorrect? Also Would i need to set a default value to text, by writing text ="" in case the user does not actually enter any word?

Furthermore, if there were existing values already in the dictionary, I want it to add to that existing list. How would this be achieved?

Also if there were already existing words in the dictionary, then how would you add onto that list, e.g. dct = {'e': 1, 'h': 1, 'l': 2, 'o': 1} and now i run in terminal >>> count_letters('hello', dct) the result would be {'e': 2, 'h': 2, 'l': 4, 'o': 2}

P. Parker
  • 1
  • 2

3 Answers3

0

If you can use Pandas, you can use value_counts():

import pandas as pd

word = "hello"
letters = [letter for letter in word]
pd.Series(letters).value_counts().to_dict()

Output:

{'e': 1, 'h': 1, 'l': 2, 'o': 1}

Otherwise, use dict and list comprehensions:

letter_ct = {letter:0 for letter in word}
for letter in word:
    letter_ct[letter] += 1
letter_ct
andrew_reece
  • 20,390
  • 3
  • 33
  • 58
  • sorry is there an alternative way because I do not know Pandas as I am not that good at python and have just started to learn it. but thanks anyway ! – P. Parker May 27 '18 at 04:58
0

You can use pythons defaultdict

from collections import defaultdict

def word_counter(word):
   word_dict = defaultdict(int)

   for letter in word:
      word_dict[letter] += 1

    return(word_dict)

print(word_counter('hello'))

Output:

defaultdict(<class 'int'>, {'h': 1, 'e': 1, 'l': 2, 'o': 1})
Simeon Ikudabo
  • 2,152
  • 1
  • 10
  • 27
-1
def count_freqs(string, dictionary={}):
  for letter in string:
    if letter not in dictionary:
      dictionary[letter] = 1
    else:
      dictionary[letter] += 1
  return dictionary
P. Parker
  • 1
  • 2
  • learn from this @Aran-Fey – P. Parker May 27 '18 at 05:31
  • You'll find that this [doesn't work correctly](https://stackoverflow.com/questions/1132941/least-astonishment-and-the-mutable-default-argument) because of the way you set `dictionary`'s default value. – Aran-Fey May 27 '18 at 05:32