Extracting the Last Element in Python
The popitem
method can be used to retrieve the last item from a dictionary. It returns a tuple of key-value pairs of the retrieved item.
Let's try it in practice. Let's say we have the following dictionary:
dct = {
'a': 1,
'b': 2,
'c': 3
}
Let's extract the last element from the dictionary:
print(dct.popitem()) # ('c', 3)
And this element will disappear from the dictionary:
print(dct) # {'a': 1, 'b': 2}
Given a dictionary:
dct = {
'x': 1,
'y': 2,
'z': 3
}
Get a tuple from it of the last element with the key, removing it from the dictionary.
Given a dictionary:
dct = {
1: 'a',
2: 'b',
3: 'c',
4: 'd',
5: 'e'
}
Write the code to get the following result:
[5, 4, 3, 2, 1]