How can I remove an element from a dictionary based on the index? For example, if I have
dict = {'s':0, 'e':1, 't':6}
I want to remove and return 's' and 0, such that the dictionary has
dict = {'e':1, 't':6}
I have tried dictionary.popitem()
that removes 't':6,
dictionary.pop(key)
removes a key from the dictionary, but I have no way of finding the key I want to remove, I only have the index.
Assuming you're doing this in Python 3.7 or later, where dict keys are ordered, you can create an iterator from the dict keys and use the next
function to obtain the first key, so that you can use the del
statement to remove that key:
d = {'s':0, 'e':1, 't':6}
del d[next(iter(d))]
print(d)
This outputs:
{'e': 1, 't': 6}
If you want to remove a key of a different index, you can use itertools.islice
to obtain the key at a given index. For example, to delete the second key (of index 1) from d
:
from itertools import islice
d = {'s':0, 'e':1, 't':6}
del d[next(islice(d, 1, None))]
print(d)
This outputs:
{'s': 0, 't': 6}