Maps in Scheme
On this page
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:
m = {}Set key/value pairs using typical name[key] = val syntax.
m["k1"] = 7
m["k2"] = 13Printing a map with, e.g., print will show all 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 is raised by default. However, you can use the get method to return a default value if the key doesn’t exist.
v3 = m.get("k3", 0)
print("v3:", v3)The built-in len function returns the number of key/value pairs when called on a map.
print("len:", len(m))To remove key/value pairs from a map, use the del statement.
del m["k2"]
print("map:", m)To remove all key/value pairs from a map, use the clear method.
m.clear()
print("map:", m)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 "".
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)There are also a number of useful utility functions for dictionaries in Python.
n2 = {"foo": 1, "bar": 2}
if n == n2:
print("n == n2")Note that dictionaries appear in the form {'k': 'v', 'k': 'v'} when printed with print.
$ python 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 == n2Now 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.
Comments powered by Disqus