How to update map keys while keeping the values sorted


I have a sorted list that contains several maps, each of those maps have a key and a value. The key of each map is a number. I want to convert this list to a map of maps but if I do that, maps get automatically ordered by a key (“1”, “2”, “3”…) and I want to keep values sorted like they are in the list. So I thought about changing the keys to “1”, “2”, “3” etc while keeping the values sorted like in the example but I can’t find a way to do it. Can someone help me here?

Current List

   %{"2" => %{"id" => "c"}},
   %{"4" => %{"id" => "e"}},
   %{"0" => %{"id" => "a"}},
   %{"3" => %{"id" => "d"}},
   %{"1" => %{"id" => "b"}}

Wanted List or Map

   %{"0" => %{"id" => "c"}},
   %{"1" => %{"id" => "e"}},
   %{"2" => %{"id" => "a"}},
   %{"3" => %{"id" => "d"}},
   %{"4" => %{"id" => "b"}}

How are you supposed to detect the unknown key from the map? What if the map in the list have multiple keys? I do not really get the example and what exactly you want to achieve.

1 Like

You have the keys, but don’t want to use them :slight_smile:

Use an index instead, maybe like this? (not tested)

|> Enum.with_index()
|> {index, %{"id"=>id}) ->
  %{index => %{"id"=>id}}

Yes, this is it, thanks a lot! :+1:

Here’s the final code

|> Enum.with_index(fn {_k, v}, index -> {to_string(index), v} end)