Menu
CoddyTech

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: 2

When 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) # 10

A 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 icon

Challenge

Easy

The 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: 1

Try 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
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