Skip to content
Advertisement

Thinkpython exercise leaves me puzzled about methods (Exercise 11.2)

“Read the documentation of the dictionary method setdefault and use it to write amore concise version of invert_dict”

A seemingly simple exercise. But it leaves me puzzeld about the interactions of methods in python.

The solution is:

    inverse = dict()
    for key in d:
        val = d[key]
        inverse.setdefault(val, []).append(key)
    return inverse

The documentation states:

setdefault(key[, default]) If key is in the dictionary, return its value. If not, insert key with a value of default and return default. default defaults to None.

And sure enough, when I test it on a dict it returns the value of key if it is already in the list. But how does .append() change the list in the dict? If the key is in the dict, setdefault returns its value, which is a list in this case. The append method works on lists, but how does it referre to the list in the dict?

Advertisement

Answer

The setdefault() method returns the value of the item with the specified key. For example:

x = { 'car': 'ford'}
y = x.setdefault('car', 'toyota')
z = x.setdefault('color', 'black')
print(y, z)
# ford black

Since the value being set in your dict is a list, this is what is returned, at which point append can be called on it.

You do have to be careful that if either the original or new values are not lists, this can throw an exception. For example:

x = { 'people': 10 }
x.setdefault('people', []).append('bob')
# AttributeError: 'int' object has no attribute 'append'
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement