Iterate over Map

To iterate over key:value pairs of Map in Go language, we may use for each loop. During each iteration we get access to key and value.

We can iterate over the key:value pairs, or just keys, or just values. In this tutorial, we will go through examples for each of these scenarios.

Examples

Iterate over key:value pairs

In the following program, we take a map from string to string, with some initial values, and iterate over the key:value pairs.

example.go

</>
Copy
package main

import "fmt"

func main() {
	x := map[string]string{
		"a": "apple",
		"b": "banana",
	}

	for key, value := range x {
		fmt.Println(key + ": " + value)
	}
}

Output

a: apple
b: banana

Iterate over keys only

In the following program, we take a map, and iterate over the keys only.

example.go

</>
Copy
package main

import "fmt"

func main() {
	map1 := map[string]string{
		"a": "apple",
		"b": "banana",
	}

	for key := range map1 {
		fmt.Println(key)
	}
}

Output

a
b

Iterate over values only

In the following program, we take a map, and iterate over the values only.

example.go

</>
Copy
package main

import "fmt"

func main() {
	map1 := map[string]string{
		"a": "apple",
		"b": "banana",
	}

	for _, value := range map1 {
		fmt.Println(value)
	}
}

Output

apple
banana

Conclusion

In this Golang Tutorial, we learned how to iterate over key:value pairs of a Map, or iterate over just keys, or iterate over values only, with the help of example programs.