Python del if in dictionary in one line
Asked Answered
C

3

13

Is there a one line way of doing the below?

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

thanks

Criticaster answered 21/2, 2012 at 11:59 Comment(3)
First thing to do with such questions: read the dict docs entirely.Heraldic
@user683111: you should accept the answer, if it worked for you :)Zipah
possible duplicate of How to remove a key from dictionary?Bewilderment
L
22

You can write

myDict.pop(key, None)
Lavonlavona answered 21/2, 2012 at 12:2 Comment(4)
It should only remove it if 'key' is in myDic (which is different than myDict)Nitza
@MichelKeijzers: Do you really think that is not a typo?Lavonlavona
If not, it would be an empty dictionary and trying to remove an item would be useless.Nitza
yeah it was a impractical example, but it was meant for didactic purposes. It helpedCriticaster
L
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
Lory answered 21/2, 2012 at 13:42 Comment(0)
K
0

Would you call this a one liner:

>>> d={1:2}
>>> if 1 in d: del d[1]
... 
>>> d
{}
Knighton answered 21/2, 2012 at 12:17 Comment(1)
I call it not one line because it's two lines, just scrunched into one in a form not permitted by PEP 8. 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).Heraldic

© 2022 - 2024 — McMap. All rights reserved.