5 ms·
This post shows up in the same day I was looking exactly at it. Quite interesting. Another way of avoiding KeyError is using dict.get(val, default_val) I f
by luizfzs 5y ago
This post shows up in the same day I was looking exactly at it. Quite interesting.
Another way of avoiding KeyError is using
dict.get(val, default_val)
I find it a bit cleaner, since you don't have to create a function or import collection.
[1] https://docs.python.org/3/library/stdtypes.html?highlight=dict#dict.get https://docs.python.org/3/library/stdtypes.html?highlight=di...
- BugsJustFindMe 5y 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 5y agoThat is a very good point! Thank you for raising that.
- deleted 5y ago[deleted]
- deleted 5y ago[deleted]
- deleted 5y ago[deleted]
- cma 5y 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 5y ago[deleted]
- BugsJustFindMe 5y 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`
- tedmiston 5y agoBut of course doing it the way you described is subtly unintuitive because it leads to either (1) duplication of the default value (or the need to pass it around as a constant to every access point) and (2) does not work anywhere the dict is accessed directly like: d['foo'] whereas defaultdict handles the default value for you correctly independently of the access method. IMO defaultdict is ideal for this use case.
- northisup 5y agoYou may also be interested in `dict.setdefault`. It has the same behavior as above but also sets the value for the key if it was previously missing. dict.setdefault(val, default_val) [1] https://docs.python.org/3/library/stdtypes.html#dict.setdefault https://docs.python.org/3/library/stdtypes.html#dict.setdefa...
- deleted 5y ago[deleted]