Golang : Check if a map (dictionary) contains a key

To check if a key exists in a map (dictionary), use a simple if statement.
If statement, while checking, for a key in a dictionary, receives two values

  • The value corresponding to the key if the key exists in a dictionary. If the key is not found, an empty string is returned.
  • Boolean value to indicate if the key exists in the dictionary. ( True if the key is found and False otherwise ).

Thus, we can write the if block as:

if value, ok := dict["key"]; ok {

}

Example :
Go ( Golang ) : Check if a key exists in a map. If it does, print its value.

package main

import "fmt"

func main() {

    dict_series_rating := map[string]float64 {"Breaking Bad" : 9.5,
                                              "Game Of Thrones" : 9.0,
                                              "Brooklyn 99" : 8.4,
                                              "Lucifer" : 8.1}

    fmt.Println("Map (dictionary) of Series / Ratings :\n", dict_series_rating)

    if len(dict_series_rating) > 0 { 
       fmt.Println("\nCount of key value pairs :", len(dict_series_rating))
    } else {
       fmt.Println("\nDictionary / Map is empty")
    }   

    if value, ok := dict_series_rating["Breaking Bad"]; ok {
        fmt.Println("\nKey (Breaking Bad) found, Value (rating) is : ", value)
    } else {
        fmt.Println("\nKey (Breaking Bad) not found.")
    }   

    value, exist := dict_series_rating["Brooklyn 99"]
    if exist {
        fmt.Println("\nKey (Brooklyn 99) found, Value (rating) is : ", value)
    } else {
        fmt.Println("\nKey (Brooklyn 99) not found.")
    }   

    if value, exist := dict_series_rating["Lucidfart"]; exist {
        fmt.Println("\nKey (Lucidfart) found, Value (rating) is : ", value)
    } else {
        fmt.Println("\nKey (Lucidfart) not found.")
    }   
}

Output

Map (dictionary) of Series / Ratings :
 map[Breaking Bad:9.5 Brooklyn 99:8.4 Game Of Thrones:9 Lucifer:8.1]

Count of key value pairs : 4

Key (Breaking Bad) found, Value (rating) is :  9.5

Key (Brooklyn 99) found, Value (rating) is :  8.4

Key (Lucidfart) not found.


Copyright (c) 2019-2021, Algotree.org.
All rights reserved.