JuliaCollections / DataStructures.jl

Julia implementation of Data structures
https://juliacollections.github.io/DataStructures.jl/latest/
MIT License
687 stars 244 forks source link

Add a delete!(::MultiDict, k, v)? #654

Open NHDaly opened 4 years ago

NHDaly commented 4 years ago

Does it make sense to add a delete!(::MultiDict, k, v) function where you can delete a specific key=>value pair?

Similar to the existing insert(::MultiDict, k, v) which inserts a specific key/value pair.

I was expecting this, and was surprised it's not offered.

NHDaly commented 4 years ago

Like, maybe something like this?:

function delete_pair!(d::MultiDict, key, val)
    vs = get(d, key, Base.secret_table_token)
    if vs !== Base.secret_table_token
        filter!(x->x≠val, vs)
    end
    isempty(vs) && delete!(d, key)
    return d
end

Unfortunately, this does a linear scan of the values vector to find the target, which isn't great. But to fix this I guess we'd have to use a different datastructure there, like a Set{V}..

NHDaly commented 3 years ago

Indeed, the golang vector-based MultiDict does exactly the above, including the terrible worst-case O(n^2) performance if you delete all pairs from the dict with the same keys, one at a time. https://github.com/jwangsadinata/go-multimap/blob/c29f3d7f33b68d8bcd82880a558e9f8eed58e2b3/slicemultimap/slicemultimap.go#L76-L88

oxinabox commented 3 years ago

I think this makes sense