4 ms·
days = {} day = '2021-05-05' if day not in days: days[day] = [] days[day].append(event) vs. just days = defaultdict(list) day = '2021-05-05'
by qwertox 6y ago
days = {}
day = '2021-05-05'
if day not in days:
days[day] = []
days[day].append(event)
vs. just
days = defaultdict(list)
day = '2021-05-05'
days[day].append(event)
what a blessing! Thanks for posting this. I do this so often.
Now maybe add an `OrderedDefaultDict`.
- deleted 6y ago[deleted]
- Xophmeister 6y agoDictionaries are ordered since, I think, 3.6. I believe this is an implementation detail of CPython, rather than it being “standard” (e.g., I don’t know if you can rely on, say, PyPy respecting that, although I suspect it does.)
- akubera 6y agoIn fact it looks like PyPy implemented it first [0], and it was an implementation detail in 3.6, but declared part of the standard in 3.7 [1]. [0]: https://docs.python.org/3.6/whatsnew/3.6.html#new-dict-implementation https://docs.python.org/3.6/whatsnew/3.6.html#new-dict-imple... [1]: https://docs.python.org/3.7/whatsnew/3.7.html https://docs.python.org/3.7/whatsnew/3.7.html
- nick238 6y agoThere's also the `setdefault` method you could use on ordinary dicts: -if day not in days: - days[day] = [] +days.setdefault(day, [])
- jhgb 6y agoInterestingly, in Common Lisp, (push event (gethash day days)) does this with zero extra effort, since the default value for fetching from a hashtable is NIL. The magic of reasonable defaults... I feel like it's underappreciated sometimes.
- kazinator 6y agoThis is the TXR Lisp interactive listener of TXR 257. Quit with :quit or Ctrl-D on an empty line. Ctrl-X ? for cheatsheet. Caution: objects in heap are farther from reality than they appear. 1> (defun pend (list item) (append list (list item))) pend 2> (define-modify-macro pendto (item) pend) pendto 3> (defvar x) x 4> (pendto x 3) (3) 5> (pendto x 4) (3 4) 6> (defvar days (hash)) days 7> (pendto [days "2021-05-01"] 'event0) (event0) 8> (pendto [days "2021-05-01"] 'event1) (event0 event1) 9> (pendto [days "2021-05-01"] 'event2) (event0 event1 event2) 10> days #H(() ("2021-05-01" (event0 event1 event2))) 11> [days "2021-05-01"] (event0 event1 event2)