by jbotz · 5y ago · 0 comments
I don't see how you can declare what the most common use of a standard function is, so, uh, citation needed.
> But what if you want to use it to count the order in which we see keys
Don't bother. Since python 3.7 (really 3.6) you can just look at the key order after adding your strings to a normal dict comprehension because dicts are ordered now.
{s: 0 for s in strings}.keys() will give you the order. If you really want a number associated with each, you can wrap that in enumerate.
In a casual discussion you don't formally "declare", you just state something based on your observations and the patterns you see in the wild, that might or might not be true in general.
Similarly, if it's a casual discussion, one can just read "the most common use case" as "a common use case", and just move on to the substance of the parent comment.
Counters are for counting, not for determining order of discovery.
d = defaultdict(lambda: len(d))
However, it's probably better to avoid defaultdict altogether and implement __missing__ in a subclass of dict.```
import itertools, collections
cnt = itertools.count(1)
d = collections.defaultdict(lambda: next(cnt))
s = "abcad"
[d[c] for c in s]
```
d = defaultdict(count().__next__)