Merge 2 lists into a map

Background

I have 2 lists with the following format:

["Div", "Season", "Date", "HomeTeam", "AwayTeam"]

["SP1", "201617", "19/08/2016", "La Coruna", "Eibar"]

My objective is to create a map with the following structure:

%{
  "Div" => "SP1",
  "Season" => 201617,
  "Date" => "19/08/2016",
  "HomeTeam" => "La Coruna",
  "AwayTeam" => "Eibar"
}

Research and difficulties

I searched for the Enum documentation and I couldn’t find any function that does this. I am also not aware of a way of doing it because the only algorithm I can currently think on is index based, and Enum functions don’t expose the indexes of the values you are currently iterating on.

Question

How can I do this?

zip the lists and then Map.new.

3 Likes

Expanding on @NobbZ’s answer:

defmodule Zip do
  def zip_it do
    list_1 = ["Div", "Season", "Date", "HomeTeam", "AwayTeam"]
    list_2 = ["SP1", "201617", "19/08/2016", "La Coruna", "Eibar"]

    list_1
    |> Enum.zip(list_2)
    |> Map.new(fn
      {"Season", num} ->
        {"Season", String.to_integer(num)}
      {"Date", << day::bytes-2, "/", month::bytes-2, "/", year::bytes-4>>} ->
        year = String.to_integer(year)
        month = String.to_integer(month)
        day = String.to_integer(day)

        {:ok, date} = Date.new(year, month, day)
        {"Date", date}
      other ->
        other
    end)
  end
end

Wil produce:

iex> Zip.zip_it
%{
  "AwayTeam" => "Eibar",
  "Date" => ~D[2016-08-19],
  "Div" => "SP1",
  "HomeTeam" => "La Coruna",
  "Season" => 201617
}
5 Likes