How to use a map in Nim

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.

Creating 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

Iterating over the table

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

Testing existence of a key

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!

Get a sequence (list) of keys

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"]

Deleting entries from the map

import strformat
import tables

var myMap = {"a": "apple", "b": "banana"}.toTable
myMap.del("a")

echo myMap

Running this yields:

{"b": "banana"}

How to pass a table into a procedure, and modify it

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

Comments

Leave a comment

What color are brown eyes? (spam prevention)
Submit
Code under MIT License unless otherwise indicated.
© 2020, Downranked, LLC.