3

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.

5
  • 1
    What do you mean by "index"? Dictionaries have keys and values, not indices. Commented Apr 2, 2019 at 17:39
  • 2
    I mean the first dictionary entry. leftmost Commented Apr 2, 2019 at 17:40
  • Dictionarys are unordered or insertordered depending on what version of python you use. There is no "leftmost" item. Commented Apr 2, 2019 at 17:42
  • duplicate - stackoverflow.com/a/40833183/5911972 Commented Apr 2, 2019 at 17:42
  • 1
    Dictionaries are only ordered in Python 3.7+, in general though, relying on the order is a sign of the wrong data-structure. But you could just iterate over it and break at the "ith" iteration, and you'll get the correct key. Note, this require O(N) time. Or just list(my_dict)[index] Commented Apr 2, 2019 at 17:42

6 Answers 6

8

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}
Sign up to request clarification or add additional context in comments.

5 Comments

What if you want the 23rd key?
not sure if this is efficient, but works for sure del d[list(d)[index]]
@ggupta By calling the list constructor you're forcing iterations over all keys of the dict, whereas with islice it can short-circuit once the desired index is reached.
@blhsing what if we want to delete at an index let's say 50?
@ggupta As pointed out by the second part of my answer, you can do del d[next(islice(d, 50, None))]
0

Quick 1 line code:

myDict = {"a":1, "b":2, "c":3}
indexToBeRemoved = 1
myDict.pop(list(myDict.keys())[indexToBeRemoved])

Comments

0

Had the same problem. idk if its right but it works on my code

grades = {
    "lance": [1, 2, 3],
    "nate": [1, 2, 3]
}

index = 0
keys = list(grades)
key = keys[index]
grades.pop(key)
print(grades)

2 Comments

Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.
This is from Review, right? I think you meant to post the "code-only answer" template, which is something like "While this code may solve the problem, it's better to include a description of how it works. Only a sentence or two might be fine. Please edit your answer."
-1

You can try converting the dict temporarily into a list and then popping like this:

for ele in list(dict1)[0]:
     dict1.pop(ele)

1 Comment

Why are you using a for-loop? That happens to work in this case since the keys are only a single-element-long, but it wouldn't work in general.
-1
dict = {'s':0, 'e':1, 't':6}

# del dict['key']
#Option 1

del dict['s']
print (dict)

#Option 2
new_dict = dict.pop('s')
print(dict)

1 Comment

The question was how to "remove an element from a dictionary based on the index". This answer is removing it by key.
-1

you can do this by iterating your dictionary.

1) if you have only one index to delete

i = 0
for key in d.keys():
    if i == 1: #assuming you want to remove the second element from the dictionary
        key_to_delete = key
    i = i + 1
if key_to_delete in d:
    del d[key_to_delete]

print(d)

2) if you have multiple indexes to delete:

i = 0
index_to_delete = [1,2] #assuming you want to remove the second and the third elements from the dictionary
keys_to_delete = []
for key in d.keys():
    if i in index_to_delete:
        keys_to_delete.append(key)
    i = i + 1

for key in keys_to_delete:
    if key in d:
        del d[key]

print(d)

3 Comments

Why are you checking if key_to_delete in d? That doesn't prevent a race condition, if that's what you had in mind (though it at least makes it smaller). Instead, put del d[key_to_delete] in a try block and except KeyError if you want to properly handle the key not existing. In this case that would be pass, but in production code, you should probably at least log it.
This isn't a terrible solution at its core, but the code is really un-idiomatic. 1) i = i + 1 should be i += 1. 2) To loop over indices and elements, use enumerate: for i, key in enumerate(d.keys()):.
If you're only doing a Python 101 course, you can stop there; otherwise, more advanced pointers: 3) If you find the one index you want (if i == 1), you should break the loop to avoid looping more than necessary. Otherwise, you might as well convert to list and select element 1: list(d.keys())[1]. 4) To get multiple elements from a list, use operator.itemgetter(*items). 5) If you have a data structure whose only purpose is membership checks, i.e. index_to_delete, use a set to get O(1) (average) lookup time.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.