Clearing everything
To delete all key-value pairs from a dictionary we can use the clear()
method. It removes literally everything from a given dictionary.
Consider the following code:
d = {'x': 1, 'y': 2, 'z': 10}
print(d) # {'x': 1, 'y': 2, 'z': 10}
# remove everything
d.clear()
print(d) # {}
First we create a dictionary d
and then print it; we see that is has two keys. Next we call d.clear()
and then once again print the dictionary. This time, we see that it has no keys - thanks to the clear()
method.
Get the value of a key
We know from dictionary basics that accessing a non-existent key from a dictionary, using bracket notation, throws an error. So what if one does want to access a key without knowing for sure whether it exists or not?
d = {'x': 1, 'y': 2, 'z': 10}
print(d['a']) # invalid!
Well one option is to use a try-except block and put the key access statement in it. Another option is to first check for the key via the in
operator and subsequently access it only if it exists in the given dictionary.
But there's even a simpler way - use the get()
method.
The get()
method takes a key and returns its value if it exists or else a default
value. The optional default
parameter itself defaults to None
.
get(key[, default])
Shown below is an example:
d = {'x': 1, 'y': 2, 'z': 10}
print(d.get('a') == None) # True
Here the expression d.get('a')
evaluates to None
since no such key exists on the dictionary d
, and likewise the comparison evaluates to True
.
get()
method to None
to get a useful output - printing None
alone doesn't print anything!Let's consider one more example, this time utilising the default
parameter:
d = {'x': 1, 'y': 2, 'z': 10}
print(d.get('a', 0)) # 0
As said earlier, if the given key doesn't exist the, default
parameter is returned. In this case, we've explicitly provided a value for default
, likewise it gets returned instead of None
.
Update a dictionary
Let's say we have an old thesaurus saved in the variable thesaurus
. As time progresses, new and updated stuff is added to these books and this is exactly what happened with our old thesaurus.
All the changes and new additions are saved in the variable thesaurus__changes
. Now to construct the latest thesaurus, we just need to update thesaurus
using thesaurus__changes
.
The question is how to do so?
This can be done very elegantly using the update()
method.
dict.update(dictionary)
The update()
method updates a dictionary with a new dictionary, supplied as an argument.
All the keys in the original dictionary that exist in dictionary
as well are updated with the new values, whereas all new keys are, obviously, added as is.
Coming back to our problem, now we know how to update our dictionary — simply call thesaurus.update(thesaurus__changes)
. New words will be added as new keys in thesaurus
whereas changes in existing words will be made by changing the values of the respective keys.
The code below generates the latest thesaurus:
thesaurus = {
'good': 'splendid, super, great',
'small': 'little, miniature, tiny'
}
thesaurus__changes = {
'small': 'minute, insignificant, short', # updated word
'bad': 'poor, faulty, imperfect', # new word
}
# update the thesaurus
thesaurus.update(thesaurus__changes)
thesaurus['small']
thesaurus['bad']
Remove key and get value
Removing a given key from a dictionary can be easily accomplished using the del
keyword, as we've seen back in dictionary basics.
However, if we want to additionally work with the key's value, using del
may not be appropriate. A better choice is to use pop()
.
dict.pop(key)
The pop()
method takes a key and removes it from the given dictionary, and returns the value corresponding to the key. If the key doesn't exists, it returns default
which defaults to None
(as in the get()
method).
In the code below, we delete the key x
from the dictionary d
and then print the deleted key-value pair:
d = {'x': 1, 'y': 2, 'z': 10}
key = 'x'
value = d.pop(key)
print('Deleted the item:', key + ':', value)
print('Dictionary d now:', d)
Remove the last item
To remove the very last item added to a dictionary, we can use the popitem()
method.
Requiring no arguments, the popitem()
method removes the last key-value pair added to a dictionary and returns it as a tuple of two elements.
If the dictionary is empty, it throws a KeyError
.
Consider the code below:
d = {'x': 1, 'y': 2, 'z': 10}
print('Removed:', d.popitem())
print('Dictionary d now:', d)
What do you think is the last item added to d
here? Trivially, it's 'z': 10
. Calling popitem()
removes this very item from the dictionary d
(as can be confirmed in line 4), and returns it (as can be confirmed in line 3).
As specified earlier, calling popitem()
on an empty dictionary throws a KeyError
exception, as follows:
# empty dictionary
d = {}
d.popitem()
Copying a dictionary
A dictionary is a mutable object and therefore stored as a reference.
This means that assigning a variable holding a dictionary to another variable would result in both the variables referring to the same dictionary.
If a change is made using one, it would be visible in the other as well. Shown below is an illustration:
d1 = {'x': 1, 'y': 2, 'z': 10}
d2 = d1
# make a change in d1
d1['x'] = 500
print(d1['x']) # 500
# the change would be visible in d2 as well
print(d2['x']) # 500
To prevent this we simply need to make a copy of the dictionary. This can be done by passing it to the dict()
function or by calling the copy()
method on the dictionary.
Let's explore the latter...
The copy()
method makes a shallow copy of a dictionary i.e it recreates all the keys and assigns them their corresponding values in the original dictionary.
Note that since the values are assigned to the keys in the new dictionary, if any value is itself stored as a reference (for e.g. a list, a tuple etc), then modifying that value using one dictionary would cause the change to be visible in the other one as well. We'll demonstrate what this means.
Consider the following code , similar to the last once, except for that now we save a copy of d1
in d2
, not its reference:
d1 = {'x': 1, 'y': 2, 'z': 10}
d2 = d1.copy()
# make a change in d1
d1['x'] = 500
print(d1['x']) # 500
# the change would not be visible in d2
print(d2['x']) # 1
Changing d1
doesn't end up doing anything to d2
— both are separate entities within their own spaces.