This question already has an answer here:
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.
</div>
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
", key)
}
}
}
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
", key)
}
}
But the first one is the idiomatic way.