dictionary - Python: dictionaries and word counting -
this question has answer here:
- item frequency count in python 10 answers
i need make function reads string , returns dictionary keys words in string , values how many times occur.
this tried:
def countwords(arg): dic = {} in agr: if in dic: dic[i] += 1 else: dic[i] = 1 return dic
which counts how many times letter appears.
i thought of separating each word different position of list first, i'm not sure how or if that's right way go here..
what should do?
this perfect case default dict: https://docs.python.org/2/library/collections.html#collections.defaultdict
import collections co def countwords(arg): dd = co.defaultdict(int) # since want counts use int in arg.split(): # split on whitespace dd[i] += 1 # when new key encountered default value entered return dd
Comments
Post a Comment