Last Updated: February 20, 2018
·
6.654K
· st3fan

Python's getdefault

How often have you grouped something together like this:

things_by_type = {}
for thing in things:
    if thing.type not in things_by_type:
        things_by_type[thing.type] = list()
    things_by_type[thing.type].append(thing)

Fortunatly there is a much nicer way to do this with
dict.setdefault. Check this out:

things_by_type = {}
for t in things:
    things_by_type.setdefault(thing.t, list()).append(t)

The trick here is that setdefault only sets the item if it does not
exist. If it does exist then it simply returns the item.

Returning the item is not super useful when you are setting a primitive type like int or str but when you are dealing with mutable containers like list or set to the list, you can immediately chain the .append or .add to them.