News for hackers. Stuff that matters.
Re:A Hodgepodge of Python by BrandonM on Thursday September 15, 2011 @09:11PM (#3002740)
I use defaultdict a lot. It's useful not only for counters, but also for sets, lists, dicts, and even other defaultdicts. It usually results in very succinct code compared to alternatives:

  occurrences = defaultdict(int)
  digraphs = defaultdict(lambda: defaultdict(int))
  
  prev_ch = None
  for ch in long_text:
    occurrences[ch] += 1
    if prev_ch is not None:
      digraphs[prev_ch][ch] += 1
    prev_ch = ch

  print "Occurrences:"
  for ch, count in sorted(occurrences.iteritems()):
    print "  %s: %i" % (ch, count)

  print "Digraph occurences:"
  for ch1, counts in sorted(digraphs):
    for ch2, count in sorted(counts):
      print "  %s%s: %i" % (ch1, ch2, count)
(I'm aware that digraphs could be done as a single flat dict; it's just a trivial example to show defaultdict nesting.)

There are no comments on this comment yet.