Dictionary Patterns
Part of the Logic & Flow section of Coddy's GDScript journey. Lesson 9 of 78.
A dictionary pattern lists keys and the patterns their values must match. It matches a dictionary that has exactly those keys, in any order:
var event := {"type": "move", "dir": "left"}
match event:
{"type": "jump"}:
print("Jump!")
{"type": "move", "dir": var d}:
print("Moving ", d)Moving leftThe value of "type" must be "move", and the value of "dir", whatever it is, is stored in d. A dictionary with a key that the pattern does not list does not match. Add .. at the end to allow extra keys:
var hit := {"type": "attack", "damage": 30, "crit": true}
match hit:
{"type": "attack", "damage": _}:
print("Exactly two keys")
{"type": "attack", "damage": var dmg, ..}:
print("Hit for ", dmg)Hit for 30A key written without a value only checks that the key exists: {"name", ..}: matches any dictionary that has a "name" key. Guards work here too: {"type": "attack", "damage": var dmg} when dmg > 50:.
Challenge
EasyThe program reads a game event written as key=value pairs separated by commas, such as type=move,dir=left, and stores it in the dictionary event (already written). All values are strings.
Use a match statement with dictionary patterns, in this order:
- Exactly the keys
type("move") anddir: printMovingand the direction - Exactly the keys
type("attack") anddamage: printTaking, the damage anddamage typeis"heal", with any other keys: printHealing- Any other dictionary with a
typekey: printUnknown event:and the type - Anything else: print
Invalid event
For the input type=attack,damage=30, the output is:
Taking 30 damageAn event such as type=move,dir=up,speed=2 has an extra key, so it prints Unknown event: move.
Try it yourself
extends Node
func _ready():
var event := {}
for pair in OS.read_string_from_stdin().split(","):
var kv := pair.split("=")
event[kv[0]] = kv[1]
# Match event against dictionary patterns
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Strings In Depth
String MethodsSearching in StringsReplace and TrimSplit and JoinRecap - Username Check4Dictionaries Part 2
Nested DictionariesArrays of DictionariesMerging DictionariesCopying DictionariesRecap - Frequency Counter2Advanced Decision Making
Match With VariablesMatch GuardsArray PatternsDictionary PatternsMembership ChecksRecap - Command Parser5Contact Book Application
Display MenuAdd Contact8Student Records Manager
Project OverviewAdd Student3Multi-dimensional Arrays
2D Arrays BasicsAccessing 2D Array ElementsNested Loops with 2D ArraysRecap - 2D ArraysJagged ArraysCommon 2D Array PatternsRecap - Game Board6Sets with Dictionaries
What is a Set?Dictionary as a SetAdding and RemovingUnion and IntersectionSet DifferenceRecap - Remove Duplicates9Advanced Data Aggregation
Summing ValuesFinding Minimum and MaximumCustom SortingRecap - Dictionary SorterPractice on your own: Online GDScript compiler