Want to create a map (also known as a dictionary or hashmap) of key-value pairs in Nim? You can do this with a table.
import tables
var myMap = initTable[string, string]()
myMap["a"] = "apple"
myMap["b"] = "banana"
echo myMap
Running this yields:
{"b": "banana", "a": "apple"}
The same map could also be created using type inference:
var myMap = {
"a": "apple",
"b": "banana"
}.toTable
The map can be iterated over as follows:
import strformat
import tables
var myMap = {"a": "apple", "b": "banana"}.toTable
for key, value in myMap:
echo fmt"key: {key}, value: {value}"
Running this yields:
key: a, value: apple
key: b, value: banana
To test whether or not a key exists:
import tables
var myMap = {"a": "apple", "b": "banana"}.toTable
if myMap.hasKey("a"):
echo "Exists!"
Running this yields:
Exists!
import strformat
import tables
var myMap = {"a": "apple", "b": "banana"}.toTable
var myKeys = newSeq[string]()
for key in myMap.keys():
myKeys.add(key)
echo myKeys
Running this yields:
@["a", "b"]
import strformat
import tables
var myMap = {"a": "apple", "b": "banana"}.toTable
myMap.del("a")
echo myMap
Running this yields:
{"b": "banana"}
import tables
proc modifyMap(map1: var Table[string, string]) =
map1["c"] = "cherry"
var myMap = {"a": "apple", "b": "banana"}.toTable
modifyMap(myMap)
echo myMap
Running this yields:
{"a": "apple", "b": "banana", "c": "cherry"}
Thank you, it's a good precise summary.
For pedagogical reasons however, these examples make it unclear which is the key type and value type need to be provided to initTable()
because both types are chosen to be the same.
As I would expect, the key type is left and the value type is right.
Leave a comment