Maps in Elm


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

To create an empty dictionary, you can use {} or dict().

m = {}

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

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

Printing a dictionary 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, a KeyError will be raised. Alternatively, you can use the get method which returns None (or a specified value) if the key is not found.

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

The built-in len function returns the number of key/value pairs when called on a dictionary.

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

The built-in del statement removes key/value pairs from a dictionary.

del m["k2"]
print("map:", m)

To remove all key/value pairs from a dictionary, use the clear method.

m.clear()
print("map:", m)

The optional second return value when getting a value from a dictionary indicates if the key was present in the dictionary. This can be used to disambiguate between missing keys and keys with zero values like 0 or "".

prs = "k2" in m
print("prs:", prs)

You can also declare and initialize a new dictionary in the same line with this syntax.

n = {"foo": 1, "bar": 2}
print("map:", n)

Note that dictionaries 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}

Next example: Functions.

查看推荐产品

Comments powered by Disqus