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:
d = {1:2, 3:4}
k = 10
if k in d:
print(d[k])
else:
print("Key", k, "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:
k = 10
d.get(k, 42)
k = 1
d.get(k, 42)
d.get(key, default)
returns d[key]
if key
is in d
, and default
otherwise. This is equivalent to
def manual_get(d, k, default):
if k in d:
return d[k]
else:
return default
dict.update()
allows us to update dictionaries using multiple entries simoultaneously.
For example:
d = {1:2, 3:4}
to_add = {5:6, 3:5}
d.update(to_add)
d
d.update(to_add)
is the same as:
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.