How can I do this more efficiently?


(Pritesh Ugrankar) #1

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.


(Yamil Bracho) #2

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)
}

(Pritesh Ugrankar) #3

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.


(Norbert Melzer) #4

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


(Pritesh Ugrankar) #5

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


(Norbert Melzer) #6

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.


(Pritesh Ugrankar) #7

Hi NobbZ,
Thanks again for taking time to answer.


(system) closed #8

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