Search code examples
pythondefaultdict

How to reset a key in a defaultdict, many times in a row?


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.


Solution

  • 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')