History of Idiom 113 > diff from v34 to v35
Edit summary for version 35 by programming-idioms.org:
[Go] +imports
[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,mymapVariables
k,x,mymapExtra Keywords
traverse traversalExtra Keywords
traverse traversalCode
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
Comments bubble