dictionary - Python: dictionaries and word counting -


this question has answer here:

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

Popular posts from this blog

ruby - Trying to change last to "x"s to 23 -

jquery - Clone last and append item to closest class -

c - Unrecognised emulation mode: elf_i386 on MinGW32 -