Update all values in a map using values from another map

How can I update all values in a map, using the values from corresponding keys of another map? For example I have the two maps bellow:

map = %{"December 2021" => 0, "November 2021" => 0, "October 2021" => 0}
map_2 = %{"December 2021" => 7, "November 2021" => 6}

And I want to update all values from map with the corresponding values from map_2, so in the end:

map = %{"December 2021" => 7, "November 2021" => 6, "October 2021" => 0}

I have tried:

Enum.map(map_2, fn {key, value} -> %{map | k => v} end)

I have also tried the code above with other functions like Map.update!/3 and similar ones, but they all return a list with maps for each iteration of Enum.map.

Does someone have any idea on how to do it?

Thanks a lot in advance!

1 Like

Try using Map.new/2, in the function you pass as the second argument you should return the key and value as a tuple.

Map.merge/2-3 ?


You need Enum.into(map2, map1, your_merge_function)

1 Like

As mentionned by @eksperimental … Map.merge could solve this.

iex> Map.merge map, map_2, fn _k, v1, v2 -> v1 + v2 end
%{"December 2021" => 7, "November 2021" => 6, "October 2021" => 0}
update = Map.take(map_2, Map.keys(map))
Map.merge(map, update)

Oh, your solution is not the same, but strictly correspond to the title :slight_smile:

Plus it is very legible :slight_smile:

It is as simple as:
Map.merge(map, map_2)

1 Like

It is not the same as the solution proposed by @ityonemo

It depends what to do with keys in map_2, not present in map :slight_smile:


Great solution! Thanks a lot. I don’t know how I haven’t seen that.

1 Like

Thanks a lot for all the help. Map.merge/2 is indeed a very simple and good solution to this specific problem.
I have thought about making a struct for it, but since the keys need to be dynamic (last 12 months), it wouldn’t work.

1 Like