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

November 30, 2021 16:11

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

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