How to sort golang Maps by value and key

Kassim Damilola
1 min readJun 18, 2020
Source: optimal workshop

This article shows how to sort golang map with the key and value

A map is an unordered list of key value pairs. Each key in a map is associated with a value. The value can be removed, modified or retrieved using its key.

In Go a map type is expressed as map[keyType]valueType

The Golang make function can be used to create maps as i

Population: = make(map[string]int) //Key type is a string while the value type is int

To add values to the population map

population:= make(map[string]int)

population[“brazil”] = 620

population[“france”] = 300

Alternately you can use the literal type

population:= map[string]int{

“brazil” :620

“france” :300

}

Let explore a larger map as in

Sorting Maps by Key

To sort my key is relatively easy, create a collection of keys and sort using the golang sort package.

Sorting Maps by value

Sorting by value is a little more complicated. The best approach is to create a struct of key and value properties.

The created struct should implement the golang sort interface making it each to sort

If the post is helpful clap. maybe twice :)

Take a Golang quiz now Check out The Ultimate Go (Golang) Programming Challenge on Udemy

--

--