Is it possible to cache the location so I don’t need to look it up twice (once in get and once in setindex!)?
"Increment the count by 1, starting from 0."
function bump!(d::Dict{K,Int}, k::K) where K
v = get(d, k, 0)
setindex!(d, v+1, k)
d
end
let
d = Dict{Int,Int}(10 => 1)
bump!(d, 10)
end
get!(collection, key, default)
Return the value stored for the given key, or if no mapping for the key is present, store key => default, and return default.
and
get!(f::Function, collection, key)
Return the value stored for the given key, or if no mapping for the key is present, store key => f(), and return f().
This is intended to be called using do block syntax.
ht_keyindex is not documented and, therefore, not part of the public interface. It should be avoided if possible, as it can disappear between any Julia versions. Does get! (the version with a bang) not cover your case?
I think not. @jar1 is asking if you can increment the value of a key in a dictionary with a single lookup. get! can set a default value if the key isn’t found, but to increment the value (if it was found) requires a second lookup in the form of d[k] += 1
Sincerely, this should be addressed by a PR to support a get! which takes a function argument that has the found value as a parameter (or default if there is nothing).
Good to know but, sincerely, I really do not like the design that is going there and it overcomplicates for the specific case discussed here, where there is a default value (and messing with nothing and Some is not needed).