2
d = defaultdict(str)
d['one'] = 'hi'
del d['one']
del d['one']

The second del raises a KeyError.

d.pop('one') has the same problem.

Is there a concise way to make the defaultdict reset-to-default a keypair?

if 'one' in d:
    del d['one']

is more verbose than I would like.

1
  • You could override defaultdict's __delitem__ method to ignore the KeyError Commented Oct 11, 2024 at 21:03

1 Answer 1

5

The below should work (pop with None)
The pop() method allows you to specify a default value that gets returned if the key is not found, avoiding a KeyError exception.

from collections import defaultdict

d = defaultdict(str)
d['one'] = 'hi'
d.pop('one', None)
d.pop('one', None)
print('Done')
Sign up to request clarification or add additional context in comments.

Comments