5 ms·
> Another way of avoiding KeyError is using dict.get(val, default_val) Except that my_dict = {} my_dict[val] = my_dict.get(val, []).append('foo') doesn
by BugsJustFindMe 6y ago
> Another way of avoiding KeyError is using dict.get(val, default_val)
Except that
my_dict = {}
my_dict[val] = my_dict.get(val, []).append('foo')
doesn't work because list.append() doesn't return anything, while
my_dict = defaultdict(list)
my_dict[val].append('foo')
does the right thing.
Defaultdict is sugar for dict.setdefault, not dict.get.
- luizfzs 6y agoThat is a very good point! Thank you for raising that.
- deleted 6y ago[deleted]
- deleted 6y ago[deleted]
- deleted 6y ago[deleted]
- cma 6y agoShouldn't the walrus operator solve this, or did they limit that to conditionals only for some reason? (my_dict[val] := my_dict.get(val, [])).append('foo')
- deleted 6y ago[deleted]
- BugsJustFindMe 6y agoHaha, probably. But counterpoints: 1) the walrus operator is stupid 2) the walrus operator is dangerous 3) `(my_dict[val] := my_dict.get(val, [])).append` is the opposite of simpler compared to `my_dict.setdefault(val, []).append` or (cleanestly) just `my_default_dict.append`