Iterating Over Dictionaries
Part of the Fundamentals section of Coddy's GDScript journey. Lesson 81 of 92.
A for loop over a dictionary gives you its keys, in the order the pairs were added. Use each key to read its value:
var stock := {"apples": 3, "pears": 5, "plums": 2}
for fruit in stock:
print(fruit, ": ", stock[fruit])The output is:
apples: 3
pears: 5
plums: 2When you need only the values, loop over values(). This loop adds up all the fruit:
var total := 0
for amount in stock.values():
total += amount
print(total) # 10A dictionary can also count things. For each word, get(word, 0) returns the count so far, or 0 the first time the word appears:
var counts := {}
for word in ["gold", "gem", "gold"]:
counts[word] = counts.get(word, 0) + 1
print(counts) # { "gold": 2, "gem": 1 }Challenge
EasyThe program reads one line of input: the loot a player picked up, separated by commas, for example gold,gem,gold.
Count how many times each item appears in a dictionary called counts. Then print each item and its count as item: count, one per line, in the order the items first appeared.
For the input gold,gem,gold,potion,gold, the output is:
gold: 3
gem: 1
potion: 1Try it yourself
extends Node
func _ready():
var loot := OS.read_string_from_stdin().split(",")
var counts := {}
# Count each item in counts
# Print each item and its count
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