Aug
30
defaultdict vs. setdefault
Stack Overflow is full of questions where the answer is to create a "multidict", a dict mapping each key to a list of values.
There are two ways to do this, using defaultdict, or using a regular dict with setdefault. And as soon as someone posts an answer using one or the other, someone else suggests they should have used the other in a comment, and sometimes it even devolves into an argument about which is better.
Compare these two functions:
def f1(pairs): d = {} for key, value in pairs: d.setdefault(key, []).append(value) return d def f2(pairs): d = collections.defaultdict(list) for key, value in csv.reader(f): d[key].append(value) return d
It's hard to argue that either one is unclear, overly verbose, hard to understand, etc.
There are two ways to do this, using defaultdict, or using a regular dict with setdefault. And as soon as someone posts an answer using one or the other, someone else suggests they should have used the other in a comment, and sometimes it even devolves into an argument about which is better.
Compare these two functions:
def f1(pairs): d = {} for key, value in pairs: d.setdefault(key, []).append(value) return d def f2(pairs): d = collections.defaultdict(list) for key, value in csv.reader(f): d[key].append(value) return d
It's hard to argue that either one is unclear, overly verbose, hard to understand, etc.