How to iterate over a collection of key-value pairs (associative array) in Go

4 Answers

0 votes
// Iterate Over Key–Value Pairs

package main

import "fmt"

func main() {
    dict := map[string]int{
        "Alice":   10,
        "Bob":     17,
        "Marley":  23,
        "Charlie": 36,
    }

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



/*
run:

Alice = 10
Bob = 17
Marley = 23
Charlie = 36

*/

 



answered Mar 22 by avibootz
0 votes
// Iterate Over Keys Only

package main

import "fmt"

func main() {
    dict := map[string]int{
        "Alice":   10,
        "Bob":     17,
        "Marley":  23,
        "Charlie": 36,
    }

    for key := range dict {
        fmt.Println("Key:", key)
    }
}



/*
run:

Key: Alice
Key: Bob
Key: Marley
Key: Charlie

*/

 



answered Mar 22 by avibootz
0 votes
// Iterate Over Values Only

package main

import "fmt"

func main() {
    dict := map[string]int{
        "Alice":   10,
        "Bob":     17,
        "Marley":  23,
        "Charlie": 36,
    }

    for _, value := range dict {
        fmt.Println("Value:", value)
    }
}



/*
run:

Value: 36
Value: 10
Value: 17
Value: 23

*/

 



answered Mar 22 by avibootz
0 votes
// Filtering While Iterating

package main

import "fmt"

func main() {
    dict := map[string]int{
        "Alice":   10,
        "Bob":     17,
        "Marley":  23,
        "Charlie": 36,
    }

    for key, value := range dict {
        if value > 21 {
            fmt.Println(key, value)
        }
    }
}



/*
run:

Marley 23
Charlie 36

*/

 



answered Mar 22 by avibootz

Related questions

...