DEV Community

myk_okoth_ogodo
myk_okoth_ogodo

Posted on

Maps : In Go-lang and Python.

This will be my second article in my "data structures in Python and Go-lang series". In my first article i talked about the word slice as applied to python and Go-lang sequences. Just to recap that topic.Slice is an in-built python function that returns a slice object that we can initialize with the arguments "start", "end" and "step" as indices, we can then use this slice object to "slice/extract" a contiguous number of elements from our sequences. In Go-lang slice is a mutable data structure that can be used to hold and manage collections of elements of a similar type. Today we talk about Maps in Go-lang an Python.

The Map data structure

Known in some quarters as associative arrays or dictionaries. Its one of the most important data structure in many programming languages, it involves the "mapping" or "associating" unique keys to their respective values.
Take for example the mapping below, made using keys as country names and their associated values as the unit of currency used in that country:

Kenya => Shilling
Austria => Euro
Belgium => Euro
Chile => Peso
China => Yuan
Denmark => Krone
America => Dollar

As illustrated above maps' keys should be unique while their values can be shared for example above both "Austria" and "Belgium" keys have a similar value of "Euro".
Unlike a standard array,our maps indices do not have to be in numeric format or consecutive. For example a normal array should look like :
countries =["Kenya","Austria","Belgium","Chile","China","Denmark","America"]

in the above case the indices to the individual elements of the array are numeric and consecutive. Such that to access the individual elements we use these numeric indices like below:

countries[0] = "Kenya"
countries[1] = "Austria"
countries[2] = "Belgium"
countries[3] = "Chile"
.....
countries[6] = "America"

PS: remember arrays in almost all the languages are zero-indexed.

However to access values in our map structure .....

Maps use an array-like syntax for indexing, unlike a standard array, indices for a map(i am using a python dictionary for illustration) need not be consecutive or numeric.

currencies = {"Kenya":"Shilling", "Austria":"Euro", "Belgium":"Euro",Chile:"Peso","China":"Yuan"]

//to access the elements;  
currencies["Kenya"]   =  "Shilling"
currencies["Austria"] =  "Euro"
currencies["Belgium"] =  "Euro"
.....
currencies["China"]   =  "Yuan"

Enter fullscreen mode Exit fullscreen mode

Creation of maps in Python and Go-lang

in python the map is implemented as an abstraction called dictionary, in which unique keys are mapped to associated values:

syntax is : identifier = {"key1":"value1","key2":"value2","key3":"value3"}

Example:

currencies = {
    "Kenya"  : "Shilling",
    "Austria": "Euro",
    "Belgium": "Euro",
    "Chile"  : "Peso",
    "China"  : "Yuan",
    "Denmark": "Krone",
    "America": "Dollar",
}
Enter fullscreen mode Exit fullscreen mode

in Go-lang maps are an unordered collection of key/value pairs, the ability to retrieve data quickly based on use keys as indices is an attractive character of maps as data stores:
Their creation involves the syntax below:

  • var identifier = map[key-type]value-type{"key1":"value1","key2":"value2","key3":"value"}

Notice above due to the strict typing nature of Golang we are explicitly stating the type of our keys and value during map instantiation.
Example:

package main
import "fmt"

var currencies = map[string]string{"Kenya":"Shilling","Austria":"Euro", "Belgium":"Euro","Chile":"Peso","China":"Yuan","America":"Dollar"}
func main(){
    fmt.Println(currencies) 
}
Enter fullscreen mode Exit fullscreen mode
  • var identifier = make(map[key-type]value-type)

Notice in the syntax above, we use the Go-lang built-in make function to create a map object.

Example:

package main
import "fmt"

func main(){
    var currencies = make(map[string]string)
    currencies["Kenya"]   = "Shilling"
    currencies["Austria"] = "Euro"
    currencies["Belgium"] = "Euro"
    currencies["Chile"]   = "Peso"
    currencies["China"]   = "Yuan"
    currencies["America"] = "Dollar"

    fmt.Println(currencies)    //will print the whole map
}
Enter fullscreen mode Exit fullscreen mode

Accessing and Assigning values in Go-lang and Python maps ....

  • In python to access and assign the values of our map, we use the keys as indices into our map,the syntax is; identifier[key] = value

For example using our currency map created above

print(currencies["Kenya"])    // will print "shilling" value
print(currencies["Austria"])  // will print "Euro" value
print(currencies["Belgium"])  // will print "Euro" value
print(currencies["Chile"])    // will print "Peso" value
print(currencies["Chine"])    // Will print "Yuan" value
print(currencies["America"])  // will print "Dollar" value
Enter fullscreen mode Exit fullscreen mode
  • In Go-lang, we use a similar indexing structure to access individual elements in our map, the syntax is: identifier[key] = value

Example:

package main
import "fmt"

func main(){
    var currencies = make(map[string]string)
    currencies["Kenya"]   = "Shilling"
    currencies["Austria"] = "Euro"
    currencies["Belgium"] = "Euro"
    currencies["Chile"]   = "Peso"

    fmt.Println(currencies["Kenya"])
    fmt.Println(currencies["Austria"])
    fmt.Println(currencies["Belgium"])
    fmt.Println(currencies["Chile"])
}

Enter fullscreen mode Exit fullscreen mode

Determining Map length in Go-lang and Python

  • In python the map class implements a len() function, that counts the number of key-value pairs

the syntax is , len(identifier)

Example

currencies = {
    "Kenya"  : "Shilling",
    "Austria": "Euro",
    "Belgium": "Euro",
    "Chile"  : "Peso",
    "China"  : "Yuan",
    "Denmark": "Krone",
    "America": "Dollar",
}

print len(currencies)   // will print out the value 7(number of currency key-value pairs)
Enter fullscreen mode Exit fullscreen mode
  • In Go-lang we stick to an identical syntax to python that looks like len(identifier)

Example

package main
import "fmt"

func main(){
    var currencies = make(map[string]string)
    currencies["Kenya"]   = "Shilling"
    currencies["Austria"] = "Euro"
    currencies["Belgium"] = "Euro"
    currencies["Chile"]   = "Peso"
    currencies["China"]   = "Yuan"
    currencies["America"] = "Dollar"

    fmt.Println(len(currencies))    //will print length of the whole map
}
Enter fullscreen mode Exit fullscreen mode

Adding items to maps in Go-lang and Python ....

  • In python to add a key-value pair to an existing map object we use the following syntax: identifier["new-key"] = "new-value"

Example


currencies = {"Kenya":"Shilling", "Austria":"Euro", "Belgium":"Euro",Chile:"Peso","China":"Yuan"}

//To add Germany Franc key value pair to the above map
currencies["Germany"] = "Franc"

print(currencies)
Enter fullscreen mode Exit fullscreen mode

The print statement will output:

{"Kenya":"Shilling", "Austria":"Euro", "Belgium":"Euro",Chile:"Peso","China":"Yuan", "Germany":"Franc"}
Enter fullscreen mode Exit fullscreen mode
  • In Go-lang to add an item to an existing map, we introduce a new index key and assigning a value to it, syntax is: indentifier["new-key"] = "new-value"

Example:
package main
import "fmt"

func main(){
    var currencies = map[string]string{"Kenya":"Shilling","Austria":"Euro","Belgium":"Euro"}
    fmt.Println(currencies)  //initial Map
    currencies["Chile"] = "Peso"  // add chile-peso key-value pair
    currencies["China"] = "Yuan"
    currencies["China"] = "Yuan"
}

Enter fullscreen mode Exit fullscreen mode

Updating a value in existing maps in Python and Go-lang ....

  • In Python you can update the value of a specific item by referring to its key name, the syntax is] identifier["old-key"] = "new-value"

Example:

currencies = {"Kenya":"Shilling", "Austria":"Euro", "Belgium":"Euro",Chile:"Peso","China":"Yuan"}

// To update the Belgium item value to "dollar"
print(currencies)   // Initial map
currencies["Belgium"] = "Dollar"
print(currencies)   // Updated map

Enter fullscreen mode Exit fullscreen mode
  • In Golang we follow a similar path to Python above

Example

package main
import "fmt"

func main(){
    var currencies = map[string]string{"Kenya":"Shilling","Austria:"Euro","Belgium":"Euro","Chile":"Peso","China":"Yuan"}
    fmt.Println(currencies)  // Initial map
    //updating the value of the Belgium key
    currencies["Belgium"] = "Dollar"
    fmt.Println(currencies)
}
Enter fullscreen mode Exit fullscreen mode

Deleting items in Go-lang and Python Maps ....

  • To delete an item in Python we use the built in del function, syntax will look like : del(identifies["key"])

Example:


currencies = {"Kenya":"Shilling", "Austria":"Euro", "Belgium":"Euro",Chile:"Peso","China":"Yuan"}
print(currencies) // initial map
del(currencies["Belgium"])
print(currencies)  // Map with Belgium deleted

Enter fullscreen mode Exit fullscreen mode

-Still in python Map we can use the built in pop function to delete an item

syntax ; identifier.pop("Key")

Example:

currencies = {"Kenya":"Shilling", "Austria":"Euro", "Belgium":"Euro",Chile:"Peso","China":"Yuan"}
print(currencies) // initial Map
// to delete the Belgium item
currencies.pop("Belgium")
print(currencies)  // Map with the Belgium item deleted

Enter fullscreen mode Exit fullscreen mode
  • In Go-lang the built-in delete function deletes an item from a given map associated with the provided key

Example

package main
import "fmt"

func main() {
    var currencies = make(map[string]string)
    currencies["Kenya"] = "Shilling"
    currencies["Austria"] = "Euro"
    currencies["Belgium"] = "Euro"
    currencies["Chile"]   = "Peso"
    currencies["China"]   = "Yuan"

     fmt.Println(currencies)
     delete(currencies, "Belgium")
     fmt.Println(currencies)
}

Enter fullscreen mode Exit fullscreen mode

Iterating over a Map in Go-lang and Python

-In Python we can use the for loop to iterate over a map using the syntax:
for key,value in range(identifier.items()) , to iterate over key,value pairs
for key in range(identifier.keys()), to iterate over keys in a map
for value in range(identifier.value()), to iterate over the values of a map

Example:

currencies = {"Kenya":"Shilling", "Austria":"Euro", "Belgium":"Euro",Chile:"Peso","China":"Yuan"}

for key,value in range(currencies.items()):
    print(key, ":" ,value)

//to print only the keys
for key in range(currencies.keys()):
    print(key)

//to print only the values
for value in range(currencies.values()):
    print(value)

Enter fullscreen mode Exit fullscreen mode
  • In Go-lang the for..range loop statement can be used to fetch the index and element of a map: syntax for key, value := range identifier{ //do something }

Example:

package main
import "fmt"

func main() {
    var currencies = map[string]string{"Kenya":"Shilling","Austria":"Euro","Belgium":"Euro","Chile":"Peso","China":"yuan","Amerika":"Dollars"}

for key,value := range currencies {
    fmt.Println("Key: ", key, "=>", "Value: ", value)
}
}
Enter fullscreen mode Exit fullscreen mode

Sorting of Map keys and Values in Golang and Python ....

  • In Go-lang we can sort kays and values of maps as follows; A keys slice is created to store keys value of map and then sort the slice. The sorted slice is used to print values of map in key order.

Example

Package main
import (
    "fmt"
    "sort"
)

func main() {
    unSortedCurrencies := map[string]string{"Kenya":"Shilling", "Austria":"Euro","Belgium":"Euro","Chile":"Peso","China":"yuan","America":"Dollar"}

keys := make([]string, 0, len(unSortedCurrencies))
for k := range unSortedCurrenciesMap{
    keys = append(keys, k)
}
sort.Strings(keys)
for _, k := range keys {
    fmt.Println(k, unSortedCurrencies[k])
}

}

Enter fullscreen mode Exit fullscreen mode

To sort Map Values


Package main
import (
    "fmt"
    "sort"
)

func main() {
    unSortedCurrencies := map[string]string{"Kenya":"Shilling", "Austria":"Euro","Belgium":"Euro","Chile":"Peso","China":"yuan","America":"Dollar"}

values := make([]string, 0, len(unSortedCurrencies))
for _,v := range unSortedCurrenciesMap{
    values = append(values, v)
}
//sort slice values
sort.String(values)

//Print values of sorted Slice
for _, v := range values {
    fmt.Println(v)
}
}
Enter fullscreen mode Exit fullscreen mode
  • In Python , we can sort our maps as follows

To sort the keys we use the in-built sorted function,
syntax : sorted(identifier)

Example:

currencies = {"Kenya":"Shilling", "Austria":"Euro", "Belgium":"Euro",Chile:"Peso","China":"Yuan"}

sortedCurrencyKeys = sorted(currencies)
print(sortedCurrencyKeys)

Enter fullscreen mode Exit fullscreen mode

To sort the values of a Map, we can use the following structure

currencies = {"Kenya":100, "Austria":200, "Belgium":110,Chile:150,"China":98}

sortedCurrencies = {k :v for k, v in sorted(currencies.items(), key=lambda item: item[1])}

Print(sortedCurrencies)

Merging two or more maps ....

  • In Go-lang we can merge two maps as shown below Example
package main
import "fmt"

func main() {
    firstCurrencies = map[string]int{"Kenya":1,"Belgium":2,"China":3}
secondCurrencies = map[string]int{"Austria":2,"Belgium":4,"Chile":6, "America":7}

for key, value := range secondCurrencies {
    firstCurrencies[key] = value
}

fmt.Println(firstCurrencies)
}

Enter fullscreen mode Exit fullscreen mode

-In python we can merge dictionaries using the method update() and also using (**)operator.

Example

firstCurrencies = {"Kenya":"Shilling","Austria":"Euro","Belgium":"Euro"}
secondCurrencies = {"Austria":"Dollar","Chile":"Peso","China":"Yuan"}

secondCurrencies.update(firstCurrencies)
print(secondCurrencies)
Enter fullscreen mode Exit fullscreen mode

using ** is a trick where a single expression is used to merge two dictionaries and stored in a third dictionary

firstCurrencies = {"Kenya":"Shilling","Austria":"Euro","Belgium":"Euro"}
secondCurrencies = {"Austria":"Dollar","Chile":"Peso","China":"Yuan"}

combinedCurrencies = {**firstCurrencies, **secondCurrencies}
print(combinedCurrencies)
Enter fullscreen mode Exit fullscreen mode

Conclusion

We have managed to look at Maps in Go-lang and Python, interrogating things like , accessing and addition of items, iterating through the items , deleting the items, merging of maps. I will continuously update this article with any information that i have overlooked into the future. Thank you. See you soon.

Top comments (0)