Logo

Programming-Idioms

History of Idiom 113 > diff from v32 to v33

Edit summary for version 33 by programming-idioms.org:
[Go] Explicit map keys are more idiomatic

Version 32

2020-05-21, 20:48:23

Version 33

2020-10-10, 13:22:35

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
import "fmt"
import "sort"
Imports
import "fmt"
import "sort"
Code
type entry struct {
	key   string
	value int
}

type entries []entry
func (list entries) Len() int { return len(list) }
func (list entries) Less(i, j int) bool { return list[i].value < list[j].value }
func (list entries) Swap(i, j int) { list[i], list[j] = list[j], list[i] }

entries := make(entries, 0, len(mymap))
for k, v := range mymap {
	entries = append(entries, entry{k, v})
}
sort.Sort(entries)

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

type entries []entry
func (list entries) Len() int { return len(list) }
func (list entries) Less(i, j int) bool { return list[i].value < list[j].value }
func (list entries) Swap(i, j int) { list[i], list[j] = list[j], list[i] }

entries := make(entries, 0, len(mymap))
for k, v := range mymap {
	entries = append(entries, entry{key: k, values: v})
}
sort.Sort(entries)

for _, e := range entries {
	fmt.Println("Key =", e.key, ", Value =", e.value)
}
Comments bubble
Define custom types entry and entries.
Then create a flat list of entries, and sort it.
Comments bubble
Define custom types entry and entries.
Then create a flat list of entries, and sort it.
Doc URL
https://golang.org/pkg/sort/#Sort
Demo URL
http://play.golang.org/p/6o--5mK_xR
Demo URL
https://play.golang.org/p/EWFqITmMSpQ