I'm currently looking at this code snippet from Think Python implementing an inverted dictionary with the setdefault method, and I'm unclear on why it works:
def invert_dict(d):
"""Inverts a dictionary, returning a map from val to a list of keys.
If the mapping key->val appears in d, then in the new dictionary
val maps to a list that includes key.
d: dict
Returns: dict
"""
inverse = {}
for key, val in d.iteritems():
inverse.setdefault(val, []).append(key)
return inverse
Reading from left to right in the for loop, inverse.setdefault(val, [])
creates an entry in the dictionary, not a list. So how can we use the append method?