Dict.merge is deprecated, what is the easiest way to combine a list of keywords with a map?

The module has Dictbeen softly deprecated since Elixir v1.2. We are now in 1.4, and this raises warnings:

Dict.merge / 2 is deprecated, use the Map module for working with maps or the Keyword module for working with keyword lists

Dict.merge worked as follows:

iex(1)> animals_keyword_list = [cats: 2, dogs: 1]
[cats: 2, dogs: 1]
iex(2)> animals_map = %{cats: 3, rabbits: 1}
%{cats: 3, rabbits: 1}
iex(3)> Dict.merge(animals_map, animals_keyword_list)
%{cats: 2, dogs: 1, rabbits: 1}

What is the best way to handle a simple keyword list → merging maps in the future?

+4
source share
2 answers

Both Mapand Keywordimplement protocols Enumerableand Collectable, therefore, we can use Enum.into/2:

iex(4)> animals_keyword_list |> Enum.into(animals_map)
%{cats: 2, dogs: 1, rabbits: 1}

. , , , , . , , :

iex(5)> animals_map |> Enum.into(animals_keyword_list)
[cats: 2, dogs: 1, cats: 3, rabbits: 1]
+9

Dict.merge/2 Map.merge/2.

map1 = %{name: "bob"}
map2 = %{name: "fred", wife: "wilma"}
Map.merge(map1, map2) # %{name: "fred", wife: "wilma"}

Keyword.merge/2.

Map.merge/2 Enum.into .

Map.merge(animal_map, Enum.into(animal_keyword_list, %{}))

Map:

Map.merge(animal_map, Map.new(animal_keyword_list))
+1

Source: https://habr.com/ru/post/1666778/


All Articles