Logo

Programming-Idioms

History of Idiom 113 > diff from v34 to v35

Edit summary for version 35 by programming-idioms.org:
[Go] +imports

Version 34

2020-10-10, 13:27:09

Version 35

2020-10-10, 13:27:34

Idiom #113 Iterate over map entries, ordered by values

Print each key k with its value x from an associative array mymap, in ascending order of x.
Note that multiple entries may exist for the same value x.

Idiom #113 Iterate over map entries, ordered by values

Print each key k with its value x from an associative array mymap, in ascending order of x.
Note that multiple entries may exist for the same value x.

Variables
k,x,mymap
Variables
k,x,mymap
Extra Keywords
traverse traversal
Extra Keywords
traverse traversal
Imports
Imports
import "fmt"
import "sort"
Code
type entry struct {
	key   string
	value int
}

entries := make([]entry, 0, len(mymap))
for k, x := range mymap {
	entries = append(entries, entry{key: k, value: x})
}
sort.Slice(entries, func(i, j int) bool {
	return entries[i].value < entries[j].value
})

for _, e := range entries {
	fmt.Println("Key =", e.key, ", Value =", e.value)
}
Code
type entry struct {
	key   string
	value int
}

entries := make([]entry, 0, len(mymap))
for k, x := range mymap {
	entries = append(entries, entry{key: k, value: x})
}
sort.Slice(entries, func(i, j int) bool {
	return entries[i].value < entries[j].value
})

for _, e := range entries {
	fmt.Println("Key =", e.key, ", Value =", e.value)
}
Comments bubble
Using sort.Slice incurs slightly less boilerplate than sort.Sort.
Comments bubble
Using sort.Slice incurs slightly less boilerplate than sort.Sort.
Doc URL
https://golang.org/pkg/sort/#Slice
Doc URL
https://golang.org/pkg/sort/#Slice
Demo URL
https://play.golang.org/p/-FoQFix9cas
Demo URL
https://play.golang.org/p/-FoQFix9cas