Menu
CoddyTech

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 left

The 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 30

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

Challenge

Easy

The 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") and dir: print Moving and the direction
  • Exactly the keys type ("attack") and damage: print Taking , the damage and damage
  • type is "heal", with any other keys: print Healing
  • Any other dictionary with a type key: print Unknown event: and the type
  • Anything else: print Invalid event

For the input type=attack,damage=30, the output is:

Taking 30 damage

An 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
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow

Practice on your own: Online GDScript compiler