I want to understand why the below code throws an error, I am trying to delete an item in a dictionary if a specific key is present.
>>>
>>> a = {1:1, 2:2}
>>> type(a)
<type 'dict'>
>>> a.has_key(1) and del a[1]
File "<stdin>", line 1
a.has_key(1) and del a[1]
^
SyntaxError: invalid syntax
>>>
The only way to make the above code work is to use
if a.has_key(1): del a[1]
delis a statement. You can’t use it as part of an expression. It’s not clear what you’re trying to do witha.has_key(1) and del a[1]anyway. Perhaps you mean:Or the alternative
a.pop(1, None)which will also remove the 1 key from the dict.