Merging two dictionaries with only keys in “b” that also exist in “a”

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