Generate a map of default values from a list

Hi,
I was trying to create a default values map from a list. e.g.
if i have a list: ids = ["a", "b", "c"], then i want %{"a" => 0, "b" => 0, "c" => 0}

I did it but not sure if is the right way. Here is how I did it.
ids |> Enum.map(fn x -> {x, 0} end) |> Map.new()

Any better way to do this?

1 Like

Map.new(ids, fn x -> {x, 0} end) or for x <- ids, into: %{}, do: {x, 0}

1 Like

It cannot get any shorter than this I guess.

iex(1)> list = ["a", "b", "c"] 
["a", "b", "c"]
iex(2)> Map.new(list, &{&1, 0})
%{"a" => 0, "b" => 0, "c" => 0}
4 Likes