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
EasyThe program reads three lines of input:
- A hero name
- A role
- 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 anint
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
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 1
Arithmetic OperatorsInteger DivisionModulo OperatorArithmetic ShortcutsRecap - Simple MathComparison Operators10Functions
Declare a FunctionArgumentsReturnReturn TypesRecap - Sigma FunctionRecap - Validation FunctionDefault Values5Operators Part 2
Logical Operators Part 1Logical Operators Part 2Recap - Simple LogicLogical Operators Part 3Ternary Operator9Loops
For LoopWhile LoopBreakContinueRecap - FactorialThe Range FunctionNested LoopRecap - Dynamic Input12Arrays Basics
Declaring an ArrayAccessing Array ElementsModifying ArraysArray MethodsRecap - Product ArrayRecap - Reversed ArrayTyped Arrays15Dictionaries
Creating DictionariesAccessing ValuesModifying DictionariesDictionary MethodsIterating Over DictionariesRecap - Inventory DictionaryPractice on your own: Online GDScript compiler