so I ran into this problem. Let's say I have a dictionary, and I want to delete the last item without knowing the item's key name. How would I do so?
CodePudding user response:
You pop the last item like this:
dictionary = {'a': 2, 'd': 3}
last_key = list(dictionary)[-1]
dictionary.pop(last_key)
print(dictionary)
Output
{'a': 2}
From Python3.7 dicts keep the order of keys. So, list(dictionary) represents keys in their insertion order
CodePudding user response:
You could probably use popitem()
(from Python 3.5 for OrderedDict, 3.7 for all dictionaries):
d = {'a':1, 'b':2,'c':3}
d.popitem() # ('c',3)
print(d)
{'a': 1, 'b': 2}
popitem() works like a LIFO queue (stack) so it removes the last added key. To delete the first item, you can use popitem(False) which works like a FIFO queue.
To delete some other arbitrary position, you can use itertools.islice to help:
from itertools import islice
d = {'a':1, 'b':2,'c':3,'d':4,'e':5}
del d[next(islice(d,2,None))] # delete at index 2
print(d)
{'a': 1, 'b': 2, 'd': 4, 'e': 5}
This still needs to run through keys sequentially but at least it doesn't create an intermediate data structure (list) to do so.
