Maps in D Programming Language
The selected target language is Python. Here’s the translated code and explanation:
Maps are Python’s built-in associative data type (sometimes called dictionaries or hashes in other languages).
To create an empty map, use the built-in dict
constructor:
Set key/value pairs using the typical name[key] = val
syntax.
Printing a map with print
will show all of its key/value pairs.
Get a value for a key with name[key]
.
If the key doesn’t exist, attempting to access it with name[key]
will raise a KeyError
. A safer way to get a value is to use the get
method, which returns None
if the key does not exist.
The built-in len
function returns the number of key/value pairs in a dictionary.
The built-in del
statement removes key/value pairs from a map.
To remove all key/value pairs from a map, you can 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’s how you can check for the presence of a key:
You can also declare and initialize a new map in the same line with this syntax.
Python’s assert
statement is useful for testing if two dictionaries are equal.
Note that maps appear in the form {'k': 'v', 'k': 'v'}
when printed with print
.
Next example: Functions.