13

Is there an easy way to delete a property of a dictionary in Python when it is possible that the property may not be present to begin with?

if the del statement is used, a KeyError is the result:

a = {}
del a['foo']
>>>KeyError: 'foo'

Its a little wordy to use an if statement and you have to type 'foo' and a twice :

a = {}
if 'foo' in a:
    del a['foo']

Looking for something similar to dict.get() that defaults to a None value if the property is not present:

a = {}
a.get('foo')  # Returns None, does not raise error
Chris Dutrow
  • 48,402
  • 65
  • 188
  • 258

1 Answers1

14

You can use dict.pop, which allows you to specify a default value to return if the key does not exist:

>>> d = {1:1, 2:2}
>>> d.pop(1, None)
1
>>> d
{2: 2}
>>> d.pop(3, None)  # No error is thrown
>>> d
{2: 2}
>>>