Accessing Map Values
We can access the value corresponding to a key in a map using the following syntax:
index
9
1
mapName["keyName"]
1mapName["keyName"]
For example:
index
99
1
2
3
4
5
6
7
8
9
10
11
12
13
14
package main
import "fmt"
func main() {
prices := map[string]int {
"apple": 100,
"banana": 120,
"peach": 170,
}
fmt.Println(prices["apple"]) // Output: 100
fmt.Println(prices["banana"]) // Output: 120
fmt.Println(prices["peach"]) // Output: 170
}
1234567891011121314package main import "fmt" func main() { prices := map[string]int { "apple": 100, "banana": 120, "peach": 170, } fmt.Println(prices["apple"]) // Output: 100 fmt.Println(prices["banana"]) // Output: 120 fmt.Println(prices["peach"]) // Output: 170 }
The expression prices["apple"]
essentially references the memory location where the value 100
is stored; hence, it acts like a variable. Therefore, we can edit the value stored at that key using the =
operator:
index
99
1
2
3
4
5
6
7
8
9
10
11
12
13
package main
import "fmt"
func main() {
prices := map[string]int {
"apple": 100,
"banana": 120,
"peach": 170,
}
prices["apple"] = 160
fmt.Println(prices["apple"]) // Output: 160
}
12345678910111213package main import "fmt" func main() { prices := map[string]int { "apple": 100, "banana": 120, "peach": 170, } prices["apple"] = 160 fmt.Println(prices["apple"]) // Output: 160 }
We can use the same assignment syntax to create a new key in the map:
pythonmapName["keyName"] = value
If the provided keyName
doesn't exist in the map, it will create and add a new key to the map with the assigned value.
index
99
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
package main
import "fmt"
func main() {
numbers := map[string]int {
"one": 1,
"two": 2,
"three": 3,
}
fmt.Println(numbers) // Output: map[one:1 three:3 two:2]
numbers["four"] = 4
fmt.Println(numbers) // Output: map[four:4 one:1 three:3 two:2]
}
1234567891011121314151617package main import "fmt" func main() { numbers := map[string]int { "one": 1, "two": 2, "three": 3, } fmt.Println(numbers) // Output: map[one:1 three:3 two:2] numbers["four"] = 4 fmt.Println(numbers) // Output: map[four:4 one:1 three:3 two:2] }
Everything was clear?
Thanks for your feedback!
Section 6. Chapter 6
Ask AI
Ask anything or try one of the suggested questions to begin our chat