Remove a dictionary property in Python that may or may not be present

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

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

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

It is not trivial to use an if statement, and you must enter 'foo' and a twice:

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

Look for something similar to dict.get() , which defaults to None if the property is missing:

 a = {} a.get('foo') # Returns None, does not raise error 
+6
source share
1 answer

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} >>> 
+9
source

Source: https://habr.com/ru/post/971568/


All Articles