
You could use the pop method on dictionary (with a default value of None for example) to remove the key only if it exists. The method returns the value associated with this key but you can ignore it. I'm not sure the __isub__ implementation would be easy to understand as it's weird to make a subtraction between a dict and a str. Even sets only support subtraction between sets. (Also you have Counter objects from collections module that implement a kind of subtraction between dicts) Le jeu. 28 avr. 2022 à 15:19, <zmvictor@gmail.com> a écrit :
*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-leave@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/BBFALX... Code of Conduct: http://python.org/psf/codeofconduct/
-- Antoine Rozo