Maps in Mercury

Our example will demonstrate how to use maps to store key/value pairs. Here’s the full source code in Python.

# To create an empty dictionary, use the built-in dict() function.
m = dict()

# Set key/value pairs using typical name[key] = val syntax.
m["k1"] = 7
m["k2"] = 13

# Printing a map with e.g. print() will show all of its key/value pairs.
print("map:", m)

# Get a value for a key with name[key].
v1 = m["k1"]
print("v1:", v1)

# If the key doesn’t exist, the default value of None is returned.
v3 = m.get("k3", None)
print("v3:", v3)

# The built-in len() function returns the number of key/value pairs when called on a map.
print("len:", len(m))

# The built-in del keyword removes key/value pairs from a map.
del m["k2"]
print("map:", m)

# To remove all key/value pairs from a map, use the clear() method.
m.clear()
print("map:", m)

# The optional second return value when getting a value from a map indicates if the key was present in the map. 
# This can be used to disambiguate between missing keys and keys with default values like 0 or "". 
# Here we didn’t need the value itself, so we used the in keyword.
_, prs = "k2" in m, m.get("k2")
print("prs:", prs)

# You can also declare and initialize a new map in the same line with this syntax.
n = {"foo": 1, "bar": 2}
print("map:", n)

# Python's collections module provides additional utility functions for specialized dictionary types.
from collections import Counter

n2 = {"foo": 1, "bar": 2}
if n == n2:
    print("n == n2")

To run the program, save the code in a file with a .py extension and use the python command.

$ python maps_example.py

Output of the code would be:

map: {'k1': 7, 'k2': 13}
v1: 7
v3: None
len: 2
map: {'k1': 7}
map: {}
prs: False
map: {'foo': 1, 'bar': 2}
n == n2

This example demonstrates how to use dictionaries in Python to perform operations similar to those shown with maps. Now that we can use and manipulate dictionaries, let’s learn more about the language.