← Back to context

Comment by quietbritishjim

7 days ago

I didn't know about the setdefault method, and wouldn't have guessed it lets you read a value. Interesting, thanks.

Another way to get data out would be to use the new | operator (i.e. x = {} | y essentially copies dictionary x to y) or the update method or ** unpacking operator (e.g. x = {**y}). But maybe those come under the umbrella of iterating as you mentioned.

setdefault was a go to method before defaultdict was added to the collections module in Python 2.5, which replaced the biggest use case.

  • It's been some time since I last benchmarked defaultdict but last time I did (circa 3.6 and less?), it was considerably slower than judicious use of setdefault.

    • One time that defaultdict may come out ahead is if the default value is expensive to construct and rarely needed:

          d.setdefault(k, computevalue())
      

      defaultdict takes a factory function, so it's only called if the key is not already present:

          d = defaultdict(computevalue)
      

      This applies to some extent even if the default value is just an empty dictionary (as it often is in my experience). You can use dict() as the factory function in that case.

      But I have never benchmarked!

      1 reply →