For example, given list
of str
: ['a', 'b', 'a', 'a', 'b']
, I want to get the counts of distinct string {'a' : 3, 'b' : 2}
.
the naive method is like following:
lst = ['a', 'b', 'a', 'a', 'b']
counts = dict()
for w in lst:
counts[w] = counts.get(w, 0) + 1
However, it needs twice Hash Table
queries. In fact, when we firstly called the get
method, we have already known the bucket location. In principle, we can modify the bucket value in-place
without searching the bucket location twice. I know in Java we can use map.merge
to get this optimization: https://stackoverflow.com/a/33711386/10969942
How to do it in Python?