[Tutor] Counting Items in a List

Martin A. Brown martin at linux-ip.net
Wed Jun 20 17:20:21 CEST 2012


Hello,

 : Sorry, it seems like I was not clear enough in that statement. I 
 : should have written something like "counting how many times each 
 : word occured" insted of "counting words".

You might like to try out collections.defaultdict().

  import collections

  summary = collections.defaultdict(int)
  for line in lines:
      words = line.strip().split()
      for word in words:
          summary[word] += 1

Lots of interesting features in the collections module...

-Martin

-- 
Martin A. Brown
http://linux-ip.net/


More information about the Tutor mailing list