GDScript Dictionary Tutorial – Complete Guide

In your journey to become an adept game developer, understanding the tools at your disposal is a critical step. One such tool, when using the Godot Engine, is GDScript’s Dictionary type. This data structure is incredibly powerful and, once fully understood, it can greatly simplify your coding tasks and improve your game performance.

What is a GDScript Dictionary?

In GDScript, a Dictionary works similarly to what other languages call an associative array. It’s a collection of key-value pairs, where each unique key maps to a specific value. This type of data structure allows you to quickly access, modify, or remove values according to their associated keys.

What is it for?

Imagine you have an inventory system in your game. Instead of having multiple arrays to handle item names, quantities, and properties, you could have a single Dictionary. In this scenario, each key represents an item name, and the value could be another Dictionary holding the item’s properties and quantity. This not only simplifies your code but also makes it faster and easier to manage.

Why should I learn it?

Utilizing Dictionaries in your game development process will streamline it. They allow for rapid data retrieval and manipulation, making for more efficient code. The more complex your game, the more valuable understanding and using Dictionaries will become. It isn’t something you want to overlook!

Now that we have grasped the value and purpose of Dictionaries in GDScript, our next sections will dive into the practical side, with hands-on coding examples. Whether you’re a complete rookie or an experienced code ninja, these upcoming tutorials will hone your skills and improve your mastery of game development.

CTA Small Image
FREE COURSES AT ZENVA
LEARN GAME DEVELOPMENT, PYTHON AND MORE
ACCESS FOR FREE
AVAILABLE FOR A LIMITED TIME ONLY

Creating a Dictionary

Creating a Dictionary in GDSCript is straightforward. You start by declaring a variable and assigning it an empty dictionary using curly braces {}. Let’s create a dictionary to represent an item in our game inventory:

var item = {}

Now we have an empty dictionary named “item”. Let’s add some properties to this item:

item["name"] = "Potion"
item["quantity"] = 5
item["type"] = "healing"

Now, our item dictionary holds three key-value pairs. Moving on, we will see how to retrieve these values using their keys.

Accessing Values in a Dictionary

To access a value in a Dictionary, we pass the associated key into the dictionary. Let’s access the name of our item:

var itemName = item["name"]
print(itemName)  # Outputs: Potion

If the key does not exist in the dictionary, Godot will return null.

Adding and Modifying Values

Adding a new key-value pair or changing an existing value in a GDScript Dictionary is simple. Just assign a new value to a key:

# Adding a new key-value pair
item["rarity"] = "rare"

# Modifying an existing value
item["quantity"] = 10

Now, if you print out the item dictionary, you will see the updated values.

Checking if a Key Exists

Before accessing a key’s value, you may want to check if the key exists in the dictionary. You can easily do so with the ‘in’ keyword:

if "rarity" in item:
    print("The item has a rarity value of: ", item["rarity"])
else:
    print("The item does not have a rarity value.")

It helps avoid errors when trying to access a non-existent key. The ‘in’ keyword returns true if the key exists in the dictionary, and false otherwise.

Removing Key-Value Pairs

There might be situations where you need to remove a key-value pair from your dictionary. The ‘erase’ method comes in handy for this:

item.erase("rarity")

This will erase the key “rarity” and its associated value from the dictionary. If the key does not exist, the method will do nothing.

Iterating Over a Dictionary

You can also iterate through all key-value pairs in a Dictionary. This is useful when you need to do something with every item in your data structure:

for key in item:
    print("Key: ", key, "Value: ", item[key])

This will print out something like:

Key: name Value: Potion
Key: quantity Value: 10
Key: type Value: healing

Nested Dictionaries

Dictionaries in GDScript can also contain other Dictionaries as values. This is useful when you need to store more complex data. Let’s have an example:

var item = {
   "name" : "Potion",
   "properties" : {
       "type" : "healing",
       "rarity" : "rare"
    },
    "quantity" : 10
}

Here, the value associated with the key “properties” is another dictionary. To access the values inside the nested dictionary, you can use the keys as indexes in a sequence:

print(item["properties"]["type"])  # Outputs: healing

Cleaning a Dictionary

Finally, if you need to remove all the key-value pairs from a Dictionary, you can use the ‘clear’ method:

item.clear()

This leaves you with an empty dictionary to fill with new values.

That’s a basic rundown on GDScript’s Dictionary type. As we’ve seen, it’s a very versatile data structure and is essential to efficient game development with Godot Engine. With these basics, you’re well on your way to becoming a more proficient game developer!

More Versatile Uses of Dictionaries

In this section, we’ll delve further into using Dictionaries in GDScript, exploring methods that help manage dictionary data, as well as handling multiple dictionaries in a more complex structure.

The Size of a Dictionary

Sometimes, you may need to count the number of key-value pairs in your Dictionary. This can be achieved using the ‘size’ method:

print(item.size())  # Outputs: 3

This outputs “3” as there are three key-value pairs in our “item” Dictionary.

Getting Keys and Values

You can obtain all the keys in a Dictionary as an array with the ‘keys’ method. Similarly, ‘values’ returns all values:

print(item.keys())   # Outputs: [name, properties, quantity]
print(item.values()) # Outputs: [Potion, {type:healing, rarity:rare}, 10]

Remember that the key and value order in a Dictionary is not guaranteed. Always use keys to access data, not their position.

Dictionaries in Arrays

You can increase the complexity and utility of these structures by combining Dictionaries with Arrays. Let’s have an inventory that holds multiple items:

var inventory = [
    {
        "name" : "Potion",
        "quantity" : 5
    },
    {
        "name" : "Sword",
        "quantity" : 1,
        "damage" : 7
    },
    {
        "name" : "Shield",
        "defense" : 3
    }
]

Our inventory is now an Array of Dictionaries. To access data, you’d need to use two indicators – one for the array index, and one for the dictionary key. For example, to get the quantity of the first item:

print(inventory[0]["quantity"])  # Outputs: 5

This prints “5”, the quantity of the first item in our inventory.

Copying Dictionaries

When copying a Dictionary, keep in mind that you’ll be copying references to the original. If you want to avoid this, use the ‘duplicate’ method:

var itemCopy = item.duplicate()

Now, ‘itemCopy’ is an independent copy of the ‘item’ Dictionary. Changes made to ‘itemCopy’ will not affect ‘item’, and vice versa.

With these methods and concepts under your belt, you are now equipped with the knowledge to manipulate complex data structures with ease! We believe in your potential and capability to build amazing and well-structured games, and wish you a fun and fulfilling programming journey ahead.

Where to go next to continue mastering Godot

Your adventure into game development doesn’t have to end here. With the knowledge you’ve gained from this tutorial, you’ve taken a colossal step in becoming a proficient game developer. If you’re keen to carry on sharpening your skills and learning even more, we can guide you there.

At Zenva, we have a wealth of resources to aid you in your journey. We offer over 250 supported courses encompassing programming, game development, and AI. Whether you’re a beginner just starting out or a veteran coder looking for some advanced lessons, Zenva has you covered. We have a range of courses complying with multiple levels of expertise.

One such course is our Godot Game Development Mini-Degree. This comprehensive collection is perfect for diving deeper into the Godot 4 engine. It covers various aspects of game development, including 2D and 3D assets, the GDScript programming language, game controls flow, player and enemy combat mechanics, and UI systems. Completing these courses will allow you to build a professional portfolio and gain highly in-demand skills for the gaming industry.

Besides, you can also find a wider range of options in our Godot Courses collection.

Don’t stop now; your journey in game development is only just beginning. Keep learning, keep coding, and take your skills to the next level with Zenva. Your future in game development is bright, and we look forward to being a part of it.

Did you come across any errors in this tutorial? Please let us know by completing this form and we’ll look into it!

FREE COURSES
Python Blog Image

FINAL DAYS: Unlock coding courses in Unity, Godot, Unreal, Python and more.