I am merging some dictionaries that come from a computation and I want to ensure that they are disjoint.
A quick way of doing it is mergewith
, eg
D1 = Dict(:a => 1, :b => 2)
D2 = Dict(:a => 4, :c => 3)
mergewith((v...) -> error("multiple values $v for some key"), D1, D2)
but that has the disadvantage that I cannot report the offending key to the user.
I am just curious if there is a way to do this with built-in functions that I missed.
(of course coding this is trivial)
function merge_disjoint(dict1::AbstractDict{K1,V1},
dict2::AbstractDict{K2,V2}) where {K1,V1,K2,V2}
K = promote_type(K1, K2)
V = promote_type(V1, V2)
result = Dict{K,V}(dict1)
for (k, v) in pairs(dict2)
if haskey(result, k)
throw(ArgumentError("key $k present in multiple dictionaries, cannot merge"))
else
result[k] = v
end
end
result
end