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:
Set key/value pairs using typical name[key] = val
syntax.
Printing a map with, for example, print
will show all of its key/value pairs.
Get a value for a key with name[key]
.
If the key doesn’t exist, the default behavior is to raise a KeyError
. To avoid this, use the get
method:
The builtin len
function returns the number of key/value pairs when called on a map.
To remove key/value pairs from a map, use the del
statement.
To remove all key/value pairs from a map, use the clear
method.
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 _
.
You can also declare and initialize a new map in the same line with this syntax.
The collections
module contains a number of useful utility classes for maps such as defaultdict
, OrderedDict
, etc.
Note that maps appear in the form {k: v, k: v}
when printed with print
.
Next example: Functions.