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:
m = {}
Set key/value pairs using the typical name[key] = val
syntax.
m["k1"] = 7
m["k2"] = 13
Printing a map with 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, 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.
v3 = m.get("k3", 0) # You can provide a default value
print("v3:", v3)
The built-in len
function returns the number of key/value pairs in a dictionary.
print("len:", len(m))
The built-in del
statement removes key/value pairs from a map.
del m["k2"]
print("map:", m)
To remove all key/value pairs from a map, you can 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’s how you can check for the presence of a key:
prs = "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)
Python’s assert
statement is useful for testing if two dictionaries are equal.
n2 = {"foo": 1, "bar": 2}
if n == n2:
print("n == n2")
Note that maps appear in the form {'k': 'v', 'k': 'v'}
when printed with print
.
$ python3 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.