-1

I'm writing a code that takes user input and counts how many times a word shows up. I need to use a dictionary because this is a school assignment.

if I had the user input something like:

"a turtle on a fence had help"

then the output would be:

{'a': 2, 'turtle': 1, 'on': 1, 'fence': 1, 'had': 1, 'help': 1}

I know that I need to add the word to the dictionary, and if it's not in there in the first place, to make the value 1. I also know that if it's in there that I need to increment the value by 1 every time after it shows up. I'm just not totally sure how to execute that process.

Caleb Collier
  • 55
  • 1
  • 3
  • 12
  • Have you tried anything? – milos.ai Oct 04 '17 at 16:41
  • 1
    I would probably split the string, then loop through it and check if the word/letter is already in the dict. If it is +=1 and if not then create a new dict item. – kstullich Oct 04 '17 at 16:42
  • This might help you, [work to dictionary](https://stackoverflow.com/questions/13003575/how-to-add-words-from-a-text-file-to-a-dictionary-depending-on-the-name) – Dharmesh Fumakiya Oct 04 '17 at 16:44

2 Answers2

4

You can have a look at Counter :

from collections import Counter

c  = "a turtle on a fence had help"

dict(Counter(c.split()))

output :

{'a': 2, 'fence': 1, 'had': 1, 'help': 1, 'on': 1, 'turtle': 1}

You need to split it on " ", because in python, strings act like imutable list. Meaning you can access the data like a list( c[0] -> "a"), but doing c[0] = "p", will raise a TypeError.

Tbaki
  • 993
  • 6
  • 12
2
>>> sentence = 'a turtle on a fence had help'
>>> output = {}
>>> for word in sentence.split():
...     if word not in output.keys():
...             output[word] = 0
...     output[word] += 1
...
>>> print(output)
{'a': 2, 'turtle': 1, 'help': 1, 'fence': 1, 'on': 1, 'had': 1}
Arount
  • 8,960
  • 1
  • 27
  • 40