Menu
CoddyTech

Creating Dictionaries

Part of the Fundamentals section of Coddy's GDScript journey. Lesson 77 of 92.

An array stores values by position. A dictionary stores values by name: each value is paired with a key, and you use the key to find the value.

Write a dictionary with curly braces. Each pair is a key, a colon and a value, and commas separate the pairs:

var player := {"name": "Mia", "hp": 100, "alive": true}
print(player)

The output shows every pair, with a space after { and before }:

{ "name": "Mia", "hp": 100, "alive": true }

Each key can appear only once in a dictionary, but values can repeat. Writing the same key twice in {} is an error that stops the program before it runs. Keys and values can be of any type: strings, numbers, booleans or even arrays.

An empty dictionary is written {}. You can add pairs to it later:

var scores := {}
print(scores) # {  }

Like arrays, dictionaries can be typed. Dictionary[String, int] means every key is a String and every value is an int:

var stock: Dictionary[String, int] = {"apples": 3, "pears": 5}
challenge icon

Challenge

Easy

The program reads three lines of input:

  1. A hero name
  2. A role
  3. A level (a whole number)

Create a dictionary called hero with three pairs:

  • "name" mapped to the hero name
  • "role" mapped to the role
  • "level" mapped to the level, stored as an int

Then print the dictionary. For the inputs Mia, Healer and 3, the output is:

{ "name": "Mia", "role": "Healer", "level": 3 }

Try it yourself

extends Node

func _ready():
	var hero_name := OS.read_string_from_stdin()
	var role := OS.read_string_from_stdin()
	var level := int(OS.read_string_from_stdin())

	# Create the hero dictionary here

	# Print the dictionary here
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals

Practice on your own: Online GDScript compiler