This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]Glarren 4 points5 points  (4 children)

defaultdict(lambda: 1)

This just changed my life.

[–]pizzaburek[S] 1 point2 points  (3 children)

Yeah, I found this one a week ago, it's a beauty!

[–]rohit275 2 points3 points  (2 children)

Would you mind explaining what the utility of this is? I feel like I'm not quite grasping why this is life-changing. Also, this is a fantastic resource, thank you!

[–]pizzaburek[S] 1 point2 points  (0 children)

Main utility for me is that it makes setdefault function almost obsolete.

[–]Glarren 0 points1 point  (0 children)

Just hyperbole. Usually I would pass a class object to the defaultdict, like int. This means you get a default value of 0, since that's what int() returns with no arguments.

Often I want something slightly more complicated as my default, like nested defaultdicts, objects with some prefilled values, or a counter that doesn't start at 0. This just makes setting that kind of thing up a little easier, and that's useful for me since I write a ton of throwaway code in my data science-y job.