Hello,
I would like to merge two dictionaries where I want to merge only keys in “b” that also exists in “a”. Is there a neat way of doing this?
Example:
a = Dict("foo" => 23, "bar" => 24)
b = Dict("bar" => 450, "unwanted1" => 23, "unwanted2" => 123)
should result in
Dict("foo" => 23, "bar" => 450)
Any hints appreciated.
Thanks!
I randomly was just programing the same, but for nestled Dicts.
function combine(A::Dict, B::Dict)
C = Dict()
for (k,v) in pairs(A)
if k in keys(B)
v2 = getindex(B, k)
if isa(v,Dict) && isa(v2,Dict)
C[k] = combine(v,v2)
else
C[k] = v2
end
else
C[k] = v
end
end
return C
end
a = Dict("foo" => 23, "bar" => 24)
b = Dict("bar" => 450, "unwanted1" => 23, "unwanted2" => 123)
combine(a,b) == Dict("foo" => 23, "bar" => 450)
For you problem, you could just use this one liner
Dict( k => (haskey(b,k) ? b[k] : v) for (k,v) in a)
(or Dict( k => (haskey(b,k) ? b[k] : a[k]) for k in keys(a))
, which might be slower but easier to read.)
2 Likes
This one liner is pretty neat, thanks!
1 Like
FWIW, a less smart option but readable:
kᵢ = intersect(keys(a), keys(b))
merge(a, Dict(k => b[k] for k in kᵢ))
Thanks! Not too bad neither. It is interesting to see the use of intersect() here.
More condensed:
merge(a, filter(x->haskey(a,x.first), b))
2 Likes