Maps in Squirrel

Maps

Maps in Python are implemented as dictionaries. Dictionaries are Python’s built-in associative data type. Here’s how we can work with dictionaries in Python:

# Create an empty dictionary
m = {}

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

# Print the dictionary to show all of its key/value pairs
print("map:", m)

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

# If the key doesn’t exist, accessing it will raise a KeyError.
# Alternatively, you can use the get method to return None or a default value if the key doesn't exist.
v3 = m.get("k3", 0)
print("v3:", v3)

# len function returns the number of key/value pairs
print("len:", len(m))

# The del statement removes key/value pairs from a dictionary
del m["k2"]
print("map:", m)

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

# The in keyword checks if the key was 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)

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

Running the above Python code will produce the following output:

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