Maps in Prolog


Maps

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

To create an empty dictionary, use the builtin dict().

# Create an empty dictionary
m = dict()

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

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

Printing a dictionary with e.g. 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, accessing it directly will raise a KeyError. You can use the get method which returns None (or a specified default) if the key is not found.

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

The builtin len returns the number of key/value pairs when called on a dictionary.

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

To remove key/value pairs from a dictionary, use the del statement.

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

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

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

You can also check if a key is present in the dictionary using the in keyword.

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

You can 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().

# Run the Python script
$ 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}

Next example: Functions.


查看推荐产品

Comments powered by Disqus