dictionarygo

Reverse a map in <value, key> format in Golang


I have a map for my program that looks like following:

fruit_map := map[string]string {
    "apple": "likey",
    "orange": "no likey",
}

I would like to reverse it so that it reads the following:

{
    "likey": "apple",
    "no likey": "orange",
}

There are no duplicates in values. Also, my map is small - about 200 keys. I did not find any built-in method to reverse a map like this. Is there any way to do this fast? I am not much bothered about space complexity, but the solution needs to be fast.

Thanks.


Solution

  • You may write a for loop to iterate over the key-value pair of original map, and put them in a new map (see function reverseMap)

    Code@https://play.golang.org/p/5y1gABTpdb8

    package main
    
    import (
        "fmt"
    )
    
    func main() {
        fruit_map := map[string]string{
            "apple":  "likey",
            "orange": "no likey",
        }
    
        reversedMap := reverseMap(fruit_map)
        fmt.Println(reversedMap)
    }
    
    func reverseMap(m map[string]string) map[string]string {
        n := make(map[string]string, len(m))
        for k, v := range m {
            n[v] = k
        }
        return n
    }
    

    Output:

    map[likey:apple no likey:orange]
    

    BTW, it is not idiomatic to name go variable like fruit_map, you really should use camel-case, like fruitMap.