13

Is there a one line way of doing the below?

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

thanks

scruffyDog
  • 721
  • 3
  • 7
  • 17

3 Answers3

22

You can write

myDict.pop(key, None)
Jochen Ritzel
  • 104,512
  • 31
  • 200
  • 194
4

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
jsbueno
  • 99,910
  • 10
  • 151
  • 209
0

Would you call this a one liner:

>>> d={1:2}
>>> if 1 in d: del d[1]
... 
>>> d
{}
Rusty Rob
  • 16,489
  • 8
  • 100
  • 116
  • 2
    I call it not one line because it's two lines, just scrunched into one in a form not permitted by [PEP 8](http://www.python.org/dev/peps/pep-0008/). Two other reasons I'd never do it this way are (a) it's not as short and pretty; (b) it requires mentioning the dictionary name and the key twice each rather than once. The same arguments apply with `d[k] if k in d else v` versus `d.get(k, v)`. – Chris Morgan Feb 21 '12 at 13:03