Check if a key exists in a map in Go
A map is a data structure and an unordered collection of key-value pairs where keys are the unique identifiers. If you are from a Python background, this is similar to a dictionary.
The main advantage of using the map is retrieving the value based on the key. However, if you try to access the key that does not exist on the map, you will get zero as the output.
Let us take an example to demonstrate the issue.
// Program to retrieve a key-value from the map
package main
import "fmt"
func main() {
// create a map
cars := map[string]int{
"Audi": 90000,
"Ford": 50000,
"Volkswagen": 70000,
"BMW": 40000}
fmt.Println("Adui Car Price:", cars["Audi"])
fmt.Println("Maruti Car Price:", cars["Maruti"])
}
Output
Adui Car Price: 90000
Maruti Car Price: 0
Check if the map has a key in Go
We can solve the problem by using the index expression.
Syntax
if val, ok := cars["Maruti"]; ok {
//do something here
}
Shorthand Syntax
This is a shorthand syntax if you just want to check if the key exists in the map.
_, exists := dict[key_name]
In Go, if
statements can be used for conditional checks and initialization statements. If we look at the above example:
- We have initialized two variables,
val
andok
. - The
val
variable will receive the value of theMaruti
from the map; otherwise, it receives zero if the value is empty. - If the
Maruti
key exists in the map, theok
variable will receivetrue
; otherwise,false
. - Next, we evaluate if the variable
ok
istrue
, and then the code block insideif
statement gets executed.
Let us now implement this in our example and retrieve the value from the map for a given key.
// Program to retrieve a key-value from the map
package main
import "fmt"
func main() {
// create a map
cars := map[string]int{
"Audi": 90000,
"Ford": 50000,
"Volkswagen": 70000,
"BMW": 40000}
if val, ok := cars["Audi"]; ok {
fmt.Println("Adui Car Price:", val)
} else {
fmt.Println("Audi Car Doesnt exist")
}
if val, ok := cars["Maruti"]; ok {
fmt.Println("Maruti Car Price:", val)
} else {
fmt.Println("Maruti Car Doesn't exist")
}
}
Output
Adui Car Price: 90000
Maruti Car Doesn't exist
Note: The value
and ok
variables are only available inside the if
block or else
block or else if
block (local scope). So you cannot access these variables outside this block.
If you want to access variables outside the if
block, we can re-write the example as shown below.
// Program to retrieve a key-value from the map
package main
import "fmt"
func main() {
// create a map
cars := map[string]int{
"Audi": 90000,
"Ford": 50000,
"Volkswagen": 70000,
"BMW": 40000}
val, ok := cars["Audi"]
if ok {
fmt.Println("Adui Car Price:", val)
} else {
fmt.Println("Audi Car Doesn't exist")
}
}
Adui Car Price: 90000
Note: Apart from the variable access there is no other change in both the examples. The first example is more compact when compared the the second example.