Removing Elements from Dictionary by Key in Python
To remove an element from a dictionary, you can use the del
operator. Let's look at an example. Let's say we have the following dictionary:
dct = {
'a': 1,
'b': 2,
'c': 3
}
Let's remove the element with key 'a'
:
del dct['a']
Let's look at the result:
print(dct) # {'b': 2, 'c': 3}
Given a dictionary:
dct = {
'x': 1,
'y': 2,
'z': 3
}
Remove from it the element with key 'x'
.
Given a dictionary:
dct = {
1: 'a',
2: 'b',
3: 'c',
4: 'd',
5: 'e'
}
Write the code to get the following result:
{1: 'a', 3: 'c', 5: 'e'}