The pop Method in Python: Key Value

The pop method returns the value of a specified key and removes it from a dictionary. If the key is not present, it returns a default value or raises an exception if no default is provided.

pop(key[, default])

  • key - the key whose value is returned.
  • default - the value returned if the key is not in the dictionary.
a = {'one': 1, 'two': 2, 'three': 3}
print(a.pop('one'))  # Output: 1, a = {'two': 2, 'three': 3}
print(a.pop('four'))  # Raises KeyError: 'four'
print(a.pop('four', 'no key'))  # Output: no key