What's the difference between Dictionary.get() and Dictionary[key]?

Godot Version

4.3

Question

So I have been messing around with using Dictionaries a bit more often in my Godot projects, mainly for reading/loading JSON files, and in using them I’ve happened upon two ways to get info from them

Say I have a Dictionary called “colors”, which lists the colors of different fruits

var colors: Dictionary = {
"apple":"red",
"tangerine":"orange"
"lemon":"yellow"
"lime":"green"
}

Now, say I want to get the color of a lemon in code. My question is, what is the difference between the two methods of getting that info, and which would be the best to use, or when should I use one over the other?

# Using Dictionary.get()
colors.get("lemon")

# Using Dictionary[key]
colors["lemon"]

.get is constant and can specify a default value, it will not error if the key is missing.

stats.get("move_speed", 200)
1 Like

So using .get is generally just a safer option then, I’m assuming. Would there be any situation where you’d might need to do (using your example) something like stats["move_speed"]?

Maybe surprisingly, creating new and/or setting values. There does not appear to be a GDScript function for adding a key/value pair outside of the operator[]

stats["move_speed"] = 250
1 Like