Python dict.pop: Removing keys with a default fallback

Python dict.pop: Removing keys with a default fallback

To remove a key-value pair from a Python dict, use dict.pop:

d = {'a':10, 'b':20}
d.pop('a')  # returns 10
d.pop('x')  # KeyError exception!

Or… pass a second argument to dict.pop. You’ll get it instead of an exception:

d.pop('x', -100)  # returns -100