Maps in Scheme
On this page
Based on the provided information, the target language is Python. Below is the translation of the Go code example to Python.
Maps
Maps are Python’s built-in associative data type, commonly known as dictionaries.
To create an empty map, use the built-in dict
function:
Set key/value pairs using typical name[key] = val
syntax.
Printing a map with, e.g., print
will show all its key/value pairs.
Get a value for a key with name[key]
.
If the key doesn’t exist, a KeyError
is raised by default. However, you can use the get
method to return a default value if the key doesn’t exist.
The built-in 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 in
operator checks if a key is present in the map. This can be used to disambiguate between missing keys and keys with zero values like 0
or ""
.
You can also declare and initialize a new map in the same line with this syntax.
There are also a number of useful utility functions for dictionaries in Python.
Note that dictionaries appear in the form {'k': 'v', 'k': 'v'}
when printed with print
.
Now that we understand basic operations on dictionaries in Python, let’s move on to learn more about the language in the next example.
Next example: Functions.