Is there a one line way of doing the below?

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

thanks

有帮助吗?

解决方案

You can write

myDict.pop(key, None)

其他提示

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
{}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top