Maps in Latex

Maps

Maps are Python’s built-in associative data type, sometimes called dictionaries or dicts in Python. Here’s the translated example code.

To create an empty dictionary in Python, use the built-in dict():

# Create an empty dictionary
m = dict()

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

# Printing a dictionary using `print` will show all 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, a `KeyError` is raised.
try:
    v3 = m["k3"]
except KeyError:
    v3 = 0  # Optional: handle the error, e.g., assign a default value
print("v3:", v3)

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

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

# Clear removes all key/value pairs from a dictionary.
m.clear()
print("map:", m)

# The `in` operator can be used to check if a key is present in the dictionary.
prs = "k2" in m
print("prs:", prs)

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

# Note: Python dictionaries can be compared for equality.
n2 = {"foo": 1, "bar": 2}
if n == n2:
    print("n == n2")

To run the program, save the code in a file named maps.py and execute it using the Python interpreter.

$ python3 maps.py
map: {'k1': 7, 'k2': 13}
v1: 7
v3: 0
len: 2
map: {'k1': 7}
map: {}
prs: False
map: {'foo': 1, 'bar': 2}
n == n2

Next example: Functions.