Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove an element from dictionary in python based on index

How can I remove an element from a dictionary based on the index? For example, if I have

d = {'s':0, 'e':1, 't':6}

I want to remove and return the first entry (leftmost), 's' and 0, such that the dictionary has

d = {'e':1, 't':6}

I have tried d.popitem() that removes 't':6. d.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.

like image 805
Coderhhz Avatar asked Mar 10 '26 19:03

Coderhhz


1 Answers

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}
like image 56
blhsing Avatar answered Mar 12 '26 08:03

blhsing