Evolution of Default Dictionaries in Python

I write a lot of code where I use a dictionary of sets (or lists or counters, etc)

Method 1

dict_set = {}

if key not in dict_set:
    dict_set[key] = set()

Method 2

dict_set = {}

dict_set.setdefault(key, set()).add(item)

Method 3

from collections import defaultdict

dict_set = defaultdict(set)


setdefault was added in Python 2.0 and I've been using (and loving) it for years.

It was only a month or two ago that I discovered collections.defaultdict. Now I use it almost every day.

UPDATE: I forgot to mention that defaultdict was added in Python 2.5. And owing to the fact that int() returns 0 you can use defaultdict(int) for a dictionary of counters.

The original post was in the category: python but I'm still in the process of migrating categories over.

The original post had 9 comments I'm in the process of migrating over.