Hacker News new | ask | show | jobs
by gamegoblin 4448 days ago
I use defaultdict all the time. Very often when describing graphs.

  g = defaultdict(dict)
Allows you to do

  g[node1][node2] = edge_weight
without checking if node1 exists, and if not, saying g[node1] = {}

Also a neat trick (of dubious use) is:

  def auto_tree(): return defaultdict(auto_tree)
Gives you infinitely nested defaultdicts.
1 comments

defaultdict is really multipurpose, quick trees is only one of the neat tricks. I like the following definition :)

    >>> Tree = lambda: defaultdict(Tree)