4. Delete keys

To remove a pair, use the del statement or the pop() method:

  • del dictionary[key] removes the pair and returns nothing. It is a statement, not a function.
  • dictionary.pop(key) removes the pair and returns its value, so you can store it in a variable.
  • Both raise KeyError when the key is missing.
  • dictionary.clear() removes every pair and returns None.

Coming from JavaScript? del d[key] is delete obj[key]. pop(key) also removes the pair and returns its value, so it is closer to getting and deleting in one step.

#01

Delete with del

Create person = {"name": "Ada", "age": 36}. Delete the pair whose key is "age" with del, then print the dictionary.

Print exactly:

Create a free account to save your progress and unlock chapter 2.

#02

Remove and return a value with pop

Create person = {"name": "Ada", "age": 36}. Remove the key "age" with pop() and store the returned value in age. Print age, then print the dictionary.

Print exactly:

Create a free account to save your progress and unlock chapter 2.

#03

pop a missing key

pop() raises KeyError when the key is not in the dictionary.

Create person = {"name": "Ada"} and call person.pop("age"). Running the code must stop with:

Create a free account to save your progress and unlock chapter 2.

#04

Remove every pair

Create data = {"a": 1, "b": 2}. Remove all pairs with clear(), then print the dictionary.

Print exactly:

Create a free account to save your progress and unlock chapter 2.