- Maps : In Go-lang and Python.
- The Map data structure
- However to access values in our map structure .
- Creation of maps in Python and Go-lang
- Accessing and Assigning values in Go-lang and Python maps .
- Determining Map length in Go-lang and Python
- Adding items to maps in Go-lang and Python .
- Updating a value in existing maps in Python and Go-lang .
- Deleting items in Go-lang and Python Maps .
- Iterating over a Map in Go-lang and Python
- Sorting of Map keys and Values in Golang and Python .
- Merging two or more maps .
- Conclusion
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.
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:
"key1":"value1","key2":"value2","key3":"value3">
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 func main()
Notice in the syntax above, we use the Go-lang built-in make function to create a map object.
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 >
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; identifierPython map add item = 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
- In Go-lang, we use a similar indexing structure to access individual elements in our map, the syntax is: identifierPython map add item = value
package main import "fmt" func main()
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)
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)
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 >
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»
currencies = //To add Germany Franc key value pair to the above map currencies["Germany"] = "Franc" print(currencies)
The print statement will output:
- 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]stringfmt.Println(currencies) //initial Map currencies["Chile"] = "Peso" // add chile-peso key-value pair currencies["China"] = "Yuan" currencies["China"] = "Yuan" >
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»
currencies = // To update the Belgium item value to "dollar" print(currencies) // Initial map currencies["Belgium"] = "Dollar" print(currencies) // Updated map
package main import "fmt" func main() < var currencies = map[string]stringfmt.Println(currencies) // Initial map //updating the value of the Belgium key currencies["Belgium"] = "Dollar" fmt.Println(currencies) >
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»])
currencies = print(currencies) // initial map del(currencies["Belgium"]) print(currencies) // Map with Belgium deleted
-Still in python Map we can use the built in pop function to delete an item
currencies = print(currencies) // initial Map // to delete the Belgium item currencies.pop("Belgium") print(currencies) // Map with the Belgium item deleted
- In Go-lang the built-in delete function deletes an item from a given map associated with the provided key
package main import "fmt" func main()
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
currencies = 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)
- 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 >
package main import "fmt" func main() < var currencies = map[string]stringfor key,value := range currencies < fmt.Println("Key: ", key, "=>", "Value: ", value) > >
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.
Package main import ( "fmt" "sort" ) func main() < unSortedCurrencies := map[string]stringkeys := 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]) >>
Package main import ( "fmt" "sort" ) func main() < unSortedCurrencies := map[string]stringvalues := 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) >>
To sort the keys we use the in-built sorted function,
syntax : sorted(identifier)
currencies = sortedCurrencyKeys = sorted(currencies) print(sortedCurrencyKeys)
To sort the values of a Map, we can use the following structure
Merging two or more maps .
package main import "fmt" func main() < firstCurrencies = map[string]intsecondCurrencies = map[string]int for key, value := range secondCurrencies < firstCurrenciesPython map add item = value >fmt.Println(firstCurrencies) >
-In python we can merge dictionaries using the method update() and also using (**)operator.
firstCurrencies = secondCurrencies = secondCurrencies.update(firstCurrencies) print(secondCurrencies)
using ** is a trick where a single expression is used to merge two dictionaries and stored in a third dictionary
firstCurrencies = secondCurrencies = combinedCurrencies = <**firstCurrencies, **secondCurrencies>print(combinedCurrencies)
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.