Python Dict problems

Max M maxm at mxm.dk
Tue Feb 3 11:57:15 CET 2004


venu gopal wrote:

> iam finding great difficulty in handling a two-dimentional dictionary or 
> any other similar data structure for the following purpose:
> from a collection of words,i need to have the count of each word so if i 
> use:
>                    str=f.getline()
>                    for l in range(flen):
>                          if subs[l].has_key(str):
>                                  subs[l][str]=1
>                          else:
>                                  subs[l][str]+=1


If it is a smalish file::

     content = f.read()
     result = {}
     for word in words:
         result[word] = content.count(word)

For big files::

     result = {}
     for l in f:
         for word in words:
             result[word] = result.get(word, 0) + l.count(word)


There are probably faster methods using re, where the counting is done 
by the reg-ex engine.


regards Max M



More information about the Python-list mailing list