To remove key-value pairs from a map in Go based on values, you need to iterate through the map and check each value. If the value matches the specified condition, remove the corresponding key-value pair.
We can remove key-value pairs from a map in Go by iterating through the map and removing pairs with a specific value.
For example,
myMap
with some key-value pairs. In this example, the map has string keys and integer values.2
.delete
function to remove the key-value pair from the map.fmt.Println
function to verify that the key-value pairs have been removed.package main
import "fmt"
func main() {
// Declare and initialize a map
myMap := map[string]int{
"one": 1,
"two": 2,
"three": 3,
"four": 2,
}
// Remove key-value pairs with specific value
for key, value := range myMap {
if value == 2 {
delete(myMap, key)
}
}
// Print the contents of the map
fmt.Println(myMap)
}
map[one:1 three:3]
We can remove key-value pairs from a map in Go by iterating through the map and removing pairs with values within a specified range.
For example,
myMap
with some key-value pairs. In this example, the map has string keys and integer values.delete
function to remove the key-value pair from the map.fmt.Println
function to verify that the key-value pairs have been removed.package main
import "fmt"
func main() {
// Declare and initialize a map
myMap := map[string]int{
"one": 1,
"two": 2,
"three": 3,
"four": 4,
}
// Remove key-value pairs with values in the range [2, 3]
for key, value := range myMap {
if value >= 2 && value <= 3 {
delete(myMap, key)
}
}
// Print the contents of the map
fmt.Println(myMap)
}
map[one:1 four:4]
We can remove key-value pairs from a map in Go by iterating through the map and removing pairs with values that meet a specified condition.
For example,
myMap
with some key-value pairs. In this example, the map has string keys and string values.delete
function to remove the key-value pair from the map.fmt.Println
function to verify that the key-value pairs have been removed.package main
import "fmt"
func main() {
// Declare and initialize a map
myMap := map[string]string{
"one": "one",
"two": "two",
"three": "three",
"four": "four",
}
// Remove key-value pairs where value length is 3
for key, value := range myMap {
if len(value) == 3 {
delete(myMap, key)
}
}
// Print the contents of the map
fmt.Println(myMap)
}
map[three:three four:four]
In this tutorial, we learned How to Remove Key-Value Pairs from a Map Based on Values in Go language with well detailed examples.