A map datatype also known as the dictionary datatype stores the data as a key, and value pairs. The syntax for declaring and initializing the values of the map using shorthand notation in go lang is shown below.
// Declaring and initializing map data type
dict := map[string][int]{"a" : 1, "b" : 2, "c" : 3}
In the above example, the keys are for string data type and values are of
int data type. The values of the map are accessed using the keys. The
following example shows accessing of the map using key.
fmt.Println(dict["b"])
Iterating a Map using For Loop and Range
Range keyword on map datatype
returns key, value pair during the iteration in a
for loop. The following example shows the iteration of the map.
package main
import "fmt"
func main() {
salesMap := map[string]int{"apple": 1000, "samsung": 2000, "sony": 1500}
for key, value := range salesMap {
fmt.Println(key, value)
}
}The output of the above program is.
apple 1000 samsung 2000 sony 1500
You can check this article on
array iteration using for loop and range.
Searching for Key existence in a Map using For Loop.
We can use the for loop to iterate over a
map and at the same time we can check for the existence of a key in the map.
The following program illustrates the key search in a Map.
package main
import "fmt"
func main() {
//Declaring and Initializing a Map
salesMap := map[string]int{"apple": 1000, "samsung": 2000, "sony": 1500}
//Iterating using for loop to check for the existence of key - samsung.
for key, _ := range salesMap {
if key == "samsung" {
fmt.Println("samsung key exists")
break
}
}
}The output of the above program is.
samsung key exists
The for loop iterates over the map and checks for the existence of the key,
samsung, in the salesMap dictionary. The disadvantage of this approach is
the iteration of the for loop. The loop has to iterate over max n times to
find out whether the key contains in the map or not.
There are better approaches to find the existence of a key in the map.
How to check if a Map contains a Key using IF Statement
A simple way is to check for the existence of a value in the map for a given
key is by using the if statement. If there is no value defined in the map, then it means that the key does
not contain in the map. The below program demonstrates the usage of the if
statement for checking the existence of key in a map.
package main
import "fmt"
func main() {
//Declare and initialize a Map
salesMap := map[string]int{"apple": 1000, "samsung": 2000, "sony": 1500}
//Access value of map for key - samsung
value := salesMap["samsung"]
// check for the existence of value. By default Go returns 0 for non existence of integer value
if value != 0 {
fmt.Println("samsung key exists")
}
//Access the values of map for key - sansui
value2 := salesMap["sansui"]
if value2 != 0 {
fmt.Println("sansui key exists")
} else {
fmt.Println("sansui key does not exist")
}
}The result of the above program is.
samsung key exists sansui key does not exist
In the above example, we have used the if statement to check for the
existence of a value in the map for the given key. As the samsung key exists
in the map, the map returns the value 2000. This value is checked against
zero value in if statement to determine the existence of key samsung.
In the case of sansui, the key doesn't exist and by default go lang returns
a zero value for non-initialization of integer datatype. The if statement
here fails and goes to the else part and prints "sansui key does not exist".
There is a disadvantage to this approach. What if we store the value of zero
against the key, sansui, then this program will give the output as the key
does not exist. See the below example.
package main
import "fmt"
func main() {
//Declare and initialize a Map
salesMap := map[string]int{"apple": 1000, "samsung": 2000, "sony": 1500, "sansui" : 0}
//Access the values of map for key - sansui
value2 := salesMap["sansui"]
if value2 != 0 {
fmt.Println("sansui key exists")
} else {
fmt.Println("sansui key does not exist")
}
}The output of the above program is.
sansui key does not exist
Even though the sansui key exists in the map, the program still gives the
non-existence result. This is due to checking against the default
values.
Check for key existence in Map using Comma Ok idiom
The Comma Ok idiom is the perfect
solution for checking the existence of a key in the map. The syntax of the
Comma Ok idiom is shown below.
//comma ok idiom syntax value, ok := dict[key]
Here the value contains the data stored against the key in the dict. The ok
is a boolean datatype. If the key contains in the map, the value will be set
to the appropriate data element and the ok will be set to true. Otherwise,
the value will be set with default data like zero for integer datatype, and
ok will be set to false.
The following example demonstrates the usage of Comma Ok idiom.
package main
import "fmt"
func main() {
salesMap := map[string]int{"apple": 1000, "samsung": 2000, "sony": 1500, "sansui": 0}
value, ok := salesMap["samsung"]
if ok {
fmt.Println("samsung key exists and value is", value)
}
value1, ok1 := salesMap["sansui"]
if ok1 {
fmt.Println("sansui key exists and value is", value1)
}
value2, ok2 := salesMap["blackberry"]
if ok2 {
fmt.Println("blackberry key exists and value is", value2)
} else {
fmt.Println("blackberry key does no exist and default value is", value2)
}
}
The execution of this program displays the below result on the console.
samsung key exists and value is 2000 sansui key exists and value is 0 blackberry key does no exist and default value is 0
We can see here, that the sansui key exists with a value zero stored in the
map and we got the correct result using the comm ok idiom. The blackberry
does not exist in the map and we got the correct result. However, the value
for this blackberry key is zero due to the default behavior of integer
datatype in go lang.
How to check if a Map contains a Key in Go Lang - The one-liner code
We can combine the comma ok idiom and the if statement in a single line and
check for the key existence. The following example shows the usage of
one-liner code.
package main
import "fmt"
func main() {
salesMap := map[string]int{"apple": 1000, "samsung": 2000, "sony": 1500}
if _, ok := salesMap["samsung"]; ok {
fmt.Println("samsung key exists")
}
}The output of the above program is .
samsung key exists
These are the multiple ways to check for the existence of a key in go lang.
If you have come across a different method, please do comment here.

Post a Comment