Is there a one line way of doing the below?
myDict = {}
if 'key' in myDic:
del myDic['key']
thanks
Use del to remove multiple keys from a dictionary Use a for-loop to iterate through a list of keys to remove. At each iteration, use the syntax del dict[key] to remove key from dict .
First, you need to convert the dictionary keys to a list using the list(dict. keys()) method. During each iteration, you can check if the value of a key is equal to the desired value. If it is True , you can issue the del statement to delete the key.
According to the python doc, you can indeed use the == operator on dictionaries.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With