3 ms·
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
by gamegoblin 13y 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.
- hcarvalhoalves 13y agodefaultdict is really multipurpose, quick trees is only one of the neat tricks. I like the following definition :) >>> Tree = lambda: defaultdict(Tree)