Maps in GDScript

Maps are built-in associative data types (sometimes called hashes or dicts in other languages).

To create an empty map, use the dictionary initializer:

var m = {}

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

m["k1"] = 7
m["k2"] = 13
print("map: ", m)

Printing a map will show all of its key/value pairs.

print("map: ", m)  # Output: {"k1": 7, "k2": 13}

Get a value for a key with name[key].

var v1 = m["k1"]
print("v1: ", v1)  # Output: v1: 7

If the key doesn’t exist, the value type returns null.

var v3 = m.get("k3")
print("v3: ", v3)  # Output: v3: null

The built-in size() method returns the number of key/value pairs when called on a map.

print("len: ", m.size())  # Output: len: 2

The built-in erase() method removes key/value pairs from a map.

m.erase("k2")
print("map: ", m)  # Output: {"k1": 7}

To remove all key/value pairs from a map, you can reinitialize the map.

m = {}
print("map: ", m)  # Output: {}

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 null. Use has() to check if a key exists.

var prs = m.has("k2")
print("prs: ", prs)  # Output: prs: false

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

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

Note that dictionaries appear in the form {k: v, k: v} when printed with print().

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