Range over dictionary always sorts

When using range and a dictionary, I always seem to get results in a case-sensitive sort by key. An answer on StackOverflow seems to indicate that go iterates maps in a random order. Is there a method to make range return dictionary elements in their original, unsorted order?

        {{- $map_test := dict
                "Key 99" "Value 99"
                "Key 2" "Value 2"
                "Key 1" "Value 1"
                "Key 3" "Value 3"
                "key 1" "Value 1 (lowercase)"

        {{ range $key, $value := $map_test }}
                <li>{{ $key }}: {{ $value }}</li>
        {{ end }}

The above returns:

  • Key 1: Value 1
  • Key 2: Value 2
  • Key 3: Value 3
  • Key 99: Value 99
  • key 1: Value 1 (lowercase)

No, there is not.


{{range pipeline}} T1 {{end}}

The value of the pipeline must be an array, slice, map, or channel. If the value of the pipeline has length zero, nothing is output; otherwise, dot is set to the successive elements of the array, slice, or map and T1 is executed. If the value is a map and the keys are of basic type with a defined order, the elements will be visited in sorted key order.

Okie doke. That seems strange, coming from other languages! How would one typically handle this use case in go?

Perhaps you can restructure your data as an array of maps.

This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.