0

I have one dictionary

a = {1:11, 2:22}

I want to check if key in b is present in a or not

b = {3:33, 1:11}

How can I do this in Go language?

I have done it like this:

a:= make(map[string][]string)
a["1"] = append(a["1"], "11")
a["1"] = append(a["1"], "22")

I have a dict b as:

b:= make(map[string]string)
b["1"] = "11"

How can I check this? Essentially, I want to check if key 1 from b is present in a or not.

Tanmay Garg
  • 801
  • 11
  • 20
sam
  • 18,509
  • 24
  • 83
  • 116

1 Answers1

8

You can either use the go idiomatic way to check for a key presence:

if _, ok:= b[key]; ok

Example:

var (
    a = map[string]int{
        "alpha": 34, "bravo": 56, "charlie": 23,
        "delta": 87, "echo": 56, "foxtrot": 12, "golf": 34, "hotel": 16,
        "indio": 87, "juliet": 65, "kilo": 43, "lima": 98}

    b = map[string]int{
        "alpha": 34, "one": 56, "charlie": 23,
        "insdio": 87, "julietta": 65, "kilo": 43, "lima": 98}
)

func main() {
    for key, _ := range a {
        if _, ok:= b[key]; ok {         
            fmt.Printf("%s\n", key)
        }
    }   
}

Playground Example 1

Or you can check if the key value from the first map corresponds to the value from the second map:

for key, val := range a {
    if val == b[key] {          
        fmt.Printf("%s\n", key)
    }
}

Playground Example 2

But the first one is the idiomatic way.

Endre Simo
  • 11,330
  • 2
  • 40
  • 49