Open In App

Remove Nth Element from Kth key's Value from the Dictionary - Python

Last Updated : 28 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

We are given a dictionary we need to remove the Nth element from the Kth key value. For example we are given a dictionary d = {'key1': ['a', 'b', 'c', 'd'], 'key2': ['w', 'x', 'y', 'z']} we need to remove the Nth element from the Kth key value so that the output should become {'key1': ['a', 'b', 'd'], 'key2': ['w', 'x', 'y', 'z']}.

Using del

To remove Nth element from the value of the Kth key in a dictionary using del you can directly access list associated with key and use del with the Nth index.

Python
# Sample dictionary
d = {'key1': ['a', 'b', 'c', 'd'], 'key2': ['w', 'x', 'y', 'z']}

K = 'key1'
N = 2

# Check if the key exists and if the value is a list
if K in d and isinstance(d[K], list) and 0 <= N < len(d[K]):
    del d[K][N]

print(d)

Output
{'key1': ['a', 'b', 'd'], 'key2': ['w', 'x', 'y', 'z']}

Explanation:

  • Code checks if key K exists in the dictionary d ensures its corresponding value is a list, and that the index N is valid.
  • If all conditions are met del statement is used to remove the element at index N from list associated with key K.

Using pop()

To remove Nth element from value of Kth key in a dictionary using pop() we can directly call the pop() method on the list associated key.

Python
d = {'key1': ['a', 'b', 'c', 'd'], 'key2': ['w', 'x', 'y', 'z']}

K = 'key1'
N = 2

# Check if the key exists and if the value is a list
if K in d and isinstance(d[K], list) and 0 <= N < len(d[K]):
    d[K].pop(N)

print(d)

Output
{'key1': ['a', 'b', 'd'], 'key2': ['w', 'x', 'y', 'z']}

Explanation:

  • Code checks if key K exists in dictionary d verifies that value is a list and ensures index N is valid.
  • If conditions are met pop() method is used to remove and return Nth element from list associated with key K.

Using List Slicing

To remove the Nth element from value of the Kth key in a dictionary using list slicing you can slice list before and after the Nth index and assign the result back to the key. This approach creates a new list without Nth element effectively removing it.

Python
# Sample dictionary
d = {'key1': ['a', 'b', 'c', 'd'], 'key2': ['w', 'x', 'y', 'z']}

K = 'key1'
N = 2

# Check if the key exists and if the value is a list
if K in d and isinstance(d[K], list) and 0 <= N < len(d[K]):
    d[K] = d[K][:N] + d[K][N+1:]

print(d)

Output
{'key1': ['a', 'b', 'd'], 'key2': ['w', 'x', 'y', 'z']}

Explanation:

  • Code checks if key K exists in the dictionary d ensures its value is a list and confirms that the index N is valid.
  • If all conditions are met it uses list slicing to create a new list by concatenating portion before the Nth index with portion after it effectively removing the Nth element.

Next Article
Practice Tags :

Similar Reads