Open In App

Remove an Element from Dictionary Based on Index in Python

Last Updated : 06 Feb, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Dictionaries do not inherently support indexing. However, if we need to remove an element based on its position, we can achieve this by converting the dictionary into an indexed structure like a list. For example, consider the dictionary d = {'a': 1, 'b': 2, 'c': 3, 'd': 4}. If we want to remove the element at index 2 (key 'c'), we can use several approaches. Let's explore different methods to remove an element from a dictionary based on its index.

Using popitem()

popitem() method removes the last key-value pair from a dictionary. By iterating through the dictionary in reverse, we can remove a specific element by index.

Python
d = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
idx = 2

# Convert dictionary to list of keys
keys = list(d.keys())

# Remove element by key
if 0 <= idx < len(keys):
    del d[keys[idx]]

print(d)

Output
{'a': 1, 'b': 2, 'd': 4}

Explanation:

  • We convert the dictionary keys into a list using list(d.keys()).
  • The desired index is validated to ensure it is within bounds.
  • The del() statement removes the element using its key.

Lets's explore some more methods and see how we can remove an element from dictionary based on index in Python.

Using Dictionary Comprehension

This method rebuilds the dictionary while skipping the key-value pair at the specified index using dictionary comprehension.

Python
# Example
d = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
idx = 2

# Convert dictionary to list of keys
keys = list(d.keys())

# Rebuild dictionary using comprehension
if 0 <= idx < len(keys):
    d = {k: d[k] for i, k in enumerate(keys) if i != idx}

print(d)

Output
{'a': 1, 'b': 2, 'd': 4}

Explanation:

  • We create a list of keys using list(d.keys()).
  • Using dictionary comprehension, we rebuild the dictionary, excluding the key at the specified index.
  • This approach does not modify the original dictionary directly but creates a new one.

Using pop() with Keys

pop() method removes a specific key from the dictionary. By converting the keys to a list, we can use the index to find and remove the key.

Python
d = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
idx = 2

# Convert dictionary to list of keys
keys = list(d.keys())

# Remove the element using pop()
if 0 <= idx < len(keys):
    d.pop(keys[idx])

print(d)

Output
{'a': 1, 'b': 2, 'd': 4}

Explanation:

  • list(d.keys()) function provides the list of keys.
  • The key at the desired index is retrieved and passed to pop(), which removes the key-value pair.

Next Article
Article Tags :
Practice Tags :

Similar Reads