Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python del if in dictionary in one line

Is there a one line way of doing the below?

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

thanks

like image 707
scruffyDog Avatar asked Feb 21 '12 11:02

scruffyDog


People also ask

How do you delete multiple elements from a dictionary?

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 .

How do you delete something from the dictionary while iterating?

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.

Can == operator be used on dictionaries?

According to the python doc, you can indeed use the == operator on dictionaries.


2 Answers

You can write

myDict.pop(key, None)
like image 131
Jochen Ritzel Avatar answered Oct 24 '22 01:10

Jochen Ritzel


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
like image 33
jsbueno Avatar answered Oct 24 '22 01:10

jsbueno