(SOLVED) Sort a dict by descending keys

Hello,

I have the following dict

{{ $Summary := dict "5" 0 "4" 0 "3" 0 "2" 0 "1" 0 "0" 0 }}

It is stored in a Scratch so as I can increment values in a range loop.

Sadly, when I do {{ range $Key, $Value := $Summary )){{ $Key }}: {{ $Value }}{{ end }}, the elements are listed in keys ascending order.

I wanted to use http://gohugo.io/functions/sort/ but somehow, a key needs to be specified in order to use the “desc” flag. I have tried to do $Summary | sort "Key" "desc" and $Summary | sort "" "desc" but I did not manage to make it work.

Also, I noticed there was no way to specify the sort order with $.Scratch.GetSortedMapValues either.

Thanks for your help!

1 Like

I solved it by doing the following:

{{ $Summary := dict "5" 0 "4" 0 "3" 0 "2" 0 "1" 0 "0" 0 }}
{{ range (seq 5 -1 0) }}
  {{ index $Summary (.|string) | default 0 }}
{{ end }}