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
0

1 Answer 1

15

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}
>>>
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.