Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to iterate through a map in Golang in order?

Tags:

go

Please see below my map

var romanNumeralDict map[int]string = map[int]string{   1000: "M",   900 : "CM",   500 : "D",   400 : "CD",   100 : "C",   90  : "XC",   50  : "L",   40  : "XL",   10  : "X",   9   : "IX",   5   : "V",   4   : "IV",   1   : "I", } 

I am looking to loop through this map in the order of the size of the key

  for k, v := range romanNumeralDict {     fmt.Println("k:", k, "v:", v)   } 

However, this prints out

k: 1000 v: M k: 40 v: XL k: 5 v: V k: 4 v: IV k: 900 v: CM k: 500 v: D k: 400 v: CD k: 100 v: C k: 90 v: XC k: 50 v: L k: 10 v: X k: 9 v: IX k: 1 v: I 

Is there a way that I can print them out in the order of the size of the key so, I would like to loop through this map like this

k:1 K:4 K:5 K:9 k:10 

etc...

Thank you very much for your help!

like image 559
samol Avatar asked Aug 20 '13 18:08

samol


People also ask

How do I iterate through a map in Golang?

The idiomatic way to iterate over a map in Go is by using the for.. range loop construct. Instead of receiving index/value pairs as with slices, you'll get key/value pairs with maps. The iteration order is intentionally randomised when you use this technique.

How do I create a sorted map in Golang?

So, to sort the keys in a map in Golang, we can create a slice of the keys and sort it and in turn sort the slice. Firstly we will iterate over the map and append all the keys in the slice. After we have all the keys we will use the sort. String function to sort the slice alphabetically.

Are Golang slices ordered?

In Go, arrays and slices are data structures that consist of an ordered sequence of elements.

How do you check if a key exists in a map Golang?

Check if Key is Present in Map in Golang To check if specific key is present in a given map in Go programming, access the value for the key in map using map[key] expression. This expression returns the value if present, and a boolean value representing if the key is present or not.


2 Answers

Collect all keys, sort them and iterate your map by key, like the following:

keys := make([]int, 0) for k, _ := range romanNumeralDict {     keys = append(keys, k) } sort.Ints(keys) for _, k := range keys {     fmt.Println(k, romanNumeralDict[k]) } 
like image 107
Volker Avatar answered Oct 25 '22 08:10

Volker


You can make it a little faster by preallocating keys because you know its length:

func sortedKeys(m map[Key]Value) ([]Key) {         keys := make([]Key, len(m))         i := 0         for k := range m {             keys[i] = k             i++         }         sort.Keys(keys)         return keys } 

Replace Key and Value with your key and value types (including the sort line). cough generics cough

Edit: Go 1.18 is finally getting generics! Here's the generic version:

// Ordered is a type constraint that matches any ordered type. // An ordered type is one that supports the <, <=, >, and >= operators. // // Note the generics proposal suggests this type will be available from // a standard "constraints" package in future. type Ordered interface {     type int, int8, int16, int32, int64,         uint, uint8, uint16, uint32, uint64, uintptr,         float32, float64,         string }  func sortedKeys[K Ordered, V any](m map[K]V) ([]K) {         keys := make([]K, len(m))         i := 0         for k := range m {             keys[i] = k             i++         }         sort.Slice(keys, func(i, j int) bool { return keys[i] < keys[j] })         return keys } 

Playground example

like image 38
Timmmm Avatar answered Oct 25 '22 09:10

Timmmm