Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

python
del
popitem
pop
communitycreator

How to remove a key value pair from a dictionary in Python

Sarah Tanveer

Dictionaries are useful data structures in Python that contain key: value pairs.

There are several ways to remove a key: value pair from a dictionary.

1. Using del

The del keyword deletes a key: value pair from a dictionary. Simply access the value that needs to be deleted and use the following syntax:


del dict[key]

If the key does not exist, a KeyError is thrown.

# declare a dictionary
dict1 = {1: "one", 2: "two", 3: "three", 4: "four"}
print("Original Dictionary: ", dict1)

# using del and giving the key as index
del dict1[1]
print("Dictionary after del: ", dict1)

# using del and giving the key as index
del dict1[3]
print("Dictionary after del: ", dict1)

2. Using popitem()

The in-built function popitem() deletes the last key: value pair in a dictionary. You cannot specify the element that needs to be deleted. The function takes no arguments.


dict.popitem()

A KeyError is thrown if the dictionary is empty. Otherwise, the key: value pair is returned as a tuple.

# declare a dictionary
dict1 = {1: "one", 2: "two", 3: "three", 4: "four"}
print("Original Dictionary: ", dict1)

# using popitem()
valDel = dict1.popitem()
print("Dictionary after using popitem(): ", dict1)
print("The key:value pair that was removed is: ", valDel)

# using popitem()
valDel = dict1.popitem()
print("Dictionary after using popitem(): ", dict1)
print("The key:value pair that was removed is: ", valDel)

3. Using pop()

The in-built function pop() deletes a specific key: value pair from a dictionary.


dict.pop(key[, default])

The function takes two arguments:

  1. key: the key of the value that needs to be deleted.

  2. default: this is an optional argument. The default value is returned if key does not exist in the dictionary

If key does not exist and the default argument is not given, a KeyError is returned. This can be avoided using the second argument.

Otherwise, if the key exists, the value of the element removed is returned.

# declare a dictionary
dict1 = {1: "one", 2: "two", 3: "three", 4: "four"}
print("Original Dictionary: ", dict1)

# using pop()
valDel = dict1.pop(1)
print("Dictionary after using pop(): ", dict1)
print("The value that was removed is: ", valDel)

# using pop()
valDel = dict1.pop(3)
print("Dictionary after using pop(): ", dict1)
print("The value that was removed is: ", valDel)

# using pop()
valDel = dict1.pop(3, "No Key Found")
print("Dictionary after using pop(): ", dict1)
print("The value that was removed is: ", valDel)

# using pop()
# if default value not given, error will be raised
print("Error raised: ")
valDel = dict1.pop(3)

RELATED TAGS

python
del
popitem
pop
communitycreator
RELATED COURSES

View all Courses

Keep Exploring