Accessing Values
Part of the Fundamentals section of Coddy's GDScript journey. Lesson 78 of 92.
To read a value, put its key in square brackets after the dictionary name:
var player := {"name": "Mia", "hp": 100}
print(player["name"]) # Mia
print(player["hp"]) # 100The key must match exactly, including capital letters: "Name" and "name" are different keys.
Reading a key that is not in the dictionary is an error, and the program stops at that line:
print(player["mana"]) # Error: the key "mana" does not existWhen a key may be missing, use get(). It returns the value of the key, or the default value you pass as the second argument when the key is missing:
print(player.get("hp", 0)) # 100
print(player.get("mana", 0)) # 0Without a default, get() returns null for a missing key, and print() shows it as <null>.
Challenge
EasyThe program reads four lines of input:
- An item name
- A price (a decimal number)
- A stock count (a whole number)
- A key to look up
Create a dictionary called item with these pairs:
"name"mapped to the item name"price"mapped to the price"stock"mapped to the stock count
Then print the value of the key from the fourth input. If the key is not in the dictionary, print Not found.
For the inputs Potion, 2.5, 15 and price, the output is:
2.5For the inputs Bow, 30.75, 7 and color, the output is:
Not foundTry it yourself
extends Node
func _ready():
var item_name := OS.read_string_from_stdin()
var price := float(OS.read_string_from_stdin())
var stock := int(OS.read_string_from_stdin())
var key := OS.read_string_from_stdin()
# Create the item dictionary here
# Print the value of key, or Not found
pass
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