Question

Is there a one line way of doing the below?

myDict = {}
if 'key' in myDic:
    del myDic['key']

thanks

Was it helpful?

Solution

You can write

myDict.pop(key, None)

OTHER TIPS

Besides the pop method one can always explictly call the __delitem__ method - which does the same as del, but is done as expression rather than as an statement. Since it is an expression, it can be combined with the inline "if" (Python's version of the C ternary operator):

d = {1:2}

d.__delitem__(1) if 1 in d else None

Would you call this a one liner:

>>> d={1:2}
>>> if 1 in d: del d[1]
... 
>>> d
{}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top