dict.get()

Suppose we want to access the value in the dictionary d that corresponds to the key k, but we don't know if the value is present in the dictionary or not. We could do it like this:

In [1]:
d = {1:2, 3:4}
k = 10
if k in d:
    print(d[k])
else:
    print("Key", k, "is not in the dictionary")
Key 10 is not in the dictionary

If we tried to avoid the if statement, and accessed k[10], that would cause an error.

Python provides us with a way to avoid using the if-statement. Instead, we can use the dict.get() function:

In [2]:
k = 10
d.get(k, 42)
Out[2]:
42
In [3]:
k = 1
d.get(k, 42)
Out[3]:
2

d.get(key, default) returns d[key] if key is in d, and default otherwise. This is equivalent to

In [4]:
def manual_get(d, k, default):
    if k in d:
        return d[k]
    else:
        return default

dict.update()

dict.update() allows us to update dictionaries using multiple entries simoultaneously.

For example:

In [5]:
d = {1:2, 3:4}
to_add = {5:6, 3:5}
d.update(to_add)
In [6]:
d
Out[6]:
{1: 2, 3: 5, 5: 6}

d.update(to_add) is the same as:

In [7]:
def manual_update(d, to_add):
    for k, v in to_add.items():
        d[k] = v

The new entries are added, and entries where the key is already in the dictionary are overwritten.