logoalt Hacker News

gpderettayesterday at 6:33 PM2 repliesview on HN

You could (and I would) make the opposite statement: upsert should be the default operator and if you want lookup only or insert only you call different operators.

I find it annoying that I often have to reach to defaultdict in Python to get this behavior.


Replies

tialaramexyesterday at 8:36 PM

C++ could offer the entry API here, so you can get back a type representing the result of finding where this key would go, and then either it has a key+value pair you can mutate if you want, or it has a blank state allowing you to write a new key+value pair if that's what you want, without redoing the potentially expensive find operation to figure out where to put the new/updated pair

hmryyesterday at 8:25 PM

I certainly use defaultdict often in Python too, but not more often than the regular dict. Maybe 90% dict and 10% defaultdict. So from my POV lookup only should definitely be the default.