Maps in Karel

Based on your instructions and the provided input, the target language extracted from the input variable karel is Python. Below is the translated Go code example to Python, formatted using Markdown suitable for Hugo.


Maps are Python’s built-in associative data type (sometimes called hashes or dicts in other languages).

To create an empty map (dict), use the builtin dict function:

m = {}

Set key/value pairs using typical name[key] = val syntax.

m["k1"] = 7
m["k2"] = 13

Printing a map with, for example, 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 behavior is to raise a KeyError. To avoid this, use the get method:

v3 = m.get("k3", 0)
print("v3:", v3)

The builtin len function returns the number of key/value pairs when called on a map.

print("len:", len(m))

To remove key/value pairs from a map, use the del statement.

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 zero values like 0 or "". Here we didn’t need the value itself, so we ignored it with the blank identifier _.

_, prs = m.get("k2"), "k2" in m
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)

The collections module contains a number of useful utility classes for maps such as defaultdict, OrderedDict, etc.

from collections import defaultdict

# Example usage of defaultdict
n2 = defaultdict(int, {"foo": 1, "bar": 2})
if n == dict(n2):
    print("n == n2")

Note that maps appear in the form {k: v, k: v} when printed with print.

$ python 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.