*Background*
It is frequently desirable to delete a dictionary entry if the key exists. It 
is necessary to check that the key exists or, alternatively, handle a KeyError: 
for, where `d` is a `dict`, and `k` is a valid hashable key, `del d[k]` raises 
KeyError if `k` does not exist. 

Example:
```
if k in d:
    del d[k]
```

*Idea*
Use the `-=` operator with the key as the right operand to delete a dictionary 
if the key exists.

*Demonstration-of-Concept*
```
class DemoDict(dict):
    def __init__(self, obj):
        super().__init__(obj)

    def __isub__(self, other):
        if other in self:
            del self[other]
            return self


if __name__ == '__main__':
    given = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
    demo = DemoDict(given)
    demo -= 'c'
    assert(demo == {'a': 1, 'b': 2, 'd': 4})
```
_______________________________________________
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/BBFALX57PJI4ALF4O6YGYMHMLNL4U4YI/
Code of Conduct: http://python.org/psf/codeofconduct/

Reply via email to