In Julia, how to merge a dictionary?
You can use merge
. If the Dict
s have elements with the same key, the value for that key will be of the last Dict
listed. If you want to combine the elements of the Dict
s that have the same key, you can use merge(combine, collection, others...)
. combine
is a function that receive two values and return a value.
Example of the docs:
julia> a = Dict("foo" => 0.0, "bar" => 42.0)
Dict{String,Float64} with 2 entries:
"bar" => 42.0
"foo" => 0.0
julia> b = Dict("baz" => 17, "bar" => 4711)
Dict{String,Int64} with 2 entries:
"bar" => 4711
"baz" => 17
julia> merge(+, a, b)
Dict{String,Float64} with 3 entries:
"bar" => 4753.0
"baz" => 17.0
"foo" => 0.0
https://docs.julialang.org/en/latest/base/collections/#Base.merge
merge(collection, others...)
Construct a merged collection from the given collections. If necessary, the types of the resulting collection will be promoted to accommodate the types of the merged collections. If the same key is present in another collection, the value for that key will be the value it has in the last collection listed.
julia> merge(dict1,dict2)
Dict{ASCIIString,Int64} with 6 entries:
"f" => 6
"c" => 3
"e" => 5
"b" => 2
"a" => 1
"d" => 4
merge!(collection, others...)
Update collection with pairs from the other collections.
julia> merge!(dict1,dict2)
Dict{ASCIIString,Int64} with 6 entries:
"f" => 6
"c" => 3
"e" => 5
"b" => 2
"a" => 1
"d" => 4
julia> dict1
Dict{ASCIIString,Int64} with 6 entries:
"f" => 6
"c" => 3
"e" => 5
"b" => 2
"a" => 1
"d" => 4