1

I have a dict where the keys map to arrays, like so:

{"A": [...], "B": [...], ...}

In a reducer function of mine I'd like to append to the value of a key, and set the key if it doesn't exist. Is there a clean way of doing this in a one-liner?

I was thinking of the following, JavaScript-style:

dict[key] = dict.get(key, []).append(val)

But forgot that .append doesn't return the list itself like a functional language would do. So the only way I see now is to have a dumb if loop check if the key exists, and create it if not... Is there a cleaner way? Thanks

NewJob
  • 59
  • 3
  • Use collections.defaultdict – Passerby Dec 03 '21 at 22:31
  • 1
    defaultdict is great, there's also the `.setdefault` method, or you can replace `.append(val)` with `+ [val]` – Alex Hall Dec 03 '21 at 22:33
  • 2
    `dict.setdefault(key,[]).append(value)` is what you're looking for OP. – ᴓᴓᴓ Dec 03 '21 at 22:33
  • @wooooooo. @Passerby. I prefer Passerby's solution, at least in this case. `defaultdict(list)` will only create the list as necessary. `dict.setdefault(key, [])` creates an empty list every time it is called, even if is thrown way most of the time. In the grand scheme of things, uselessly creating an empty list isn't necessarily a big deal, but still a waste of space. – Frank Yellin Dec 03 '21 at 22:45
  • If you're that worried about performance, use cython :D (I'm joking, that seems reasonable, but I have no idea how defaultdict works internally). Looks like it is indeed faster: https://stackoverflow.com/questions/12555967/is-the-defaultdict-in-pythons-collections-module-really-faster-than-using-setde – ᴓᴓᴓ Dec 03 '21 at 22:53

0 Answers0