How can I do this more efficiently?

Hi,

I am trying to compare two maps, and then delete the duplicates from the second map.
Here’s what I’ve tried:

package main

import "fmt"

func main() {
	testMap := map[string]string{
		"first":  "David",
		"middle": "Scott",
		"last":   "Mustaine",
	}

	fmt.Printf("testMap: %v\n", testMap)
	uniqueMap := map[string]string{
		"first":  "David",
		"middle": "Scott",
	}
	fmt.Printf("uniqueMap Before: %v\n", uniqueMap)
	for key, _ := range testMap {
		_, ok := uniqueMap[key]
		if ok == false {
			uniqueMap[key] = testMap[key]
		} else {
			delete(uniqueMap, key)
		}
	}
	fmt.Printf("uniqueMap After: %v\n", uniqueMap)
}

And here is the output:

>go run main.go
testMap: map[first:David last:Mustaine middle:Scott]
uniqueMap Before: map[first:David middle:Scott]
uniqueMap After: map[last:Mustaine]

Is there a better way to do this? I might need to run this on a map with a lot of key value pairs and hence the request.

1 Like

Maybe

package main

import "fmt"

func unique(source map[string]string, target map[string]string) map[string]string {
	for key, value := range source {
		if _, ok := target [key]; ok == false {
			target [key] = value
		} else {
			delete(target , key)
		}
	}
	
	return target
}

func main() {
	testMap := map[string]string{
		"first":  "David",
		"middle": "Scott",
		"last":   "Mustaine",
	}

	fmt.Printf("testMap: %v\n", testMap)
	
	uniqueMap := map[string]string{
		"first":  "David",
		"middle": "Scott",
	}
	fmt.Printf("uniqueMap Before: %v\n", uniqueMap)
	
	uniqueMap = unique(testMap, uniqueMap)
	fmt.Printf("uniqueMap After: %v\n", uniqueMap)
}
2 Likes

Hi Yamil,

Thank you very much…especially for this line:

if _, ok := target [key]; ok == false

Also thanks for suggesting to put this in a function. It appears that using functions is encouraged in golang. May be it’s a “best practice” for all programming languages, but I am not a developer, so learning a lot here.
Also, I would like to thank you for your patience and tenacity to help.

1 Like

Might be a personal thing, bit I prefer !ok over ok == false

3 Likes

Hi NobbZ,
I guess both would mean the same or is one more accurate/faster than the other?

1 Like

Im pretty sure that there is no measurable performance impact. I just prefer the ! because it’s less verbose, other prefer comparing with true and false explicitly because it’s clear when reading the code.

2 Likes

Hi NobbZ,
Thanks again for taking time to answer.

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.