Menu
CoddyTech

Nested Dictionaries

Part of the Logic & Flow section of Coddy's GDScript journey. Lesson 19 of 78.

A dictionary value can be another dictionary. A nested dictionary groups related data: the outer keys name the records, and each inner dictionary holds the fields of one record.

var heroes := {
	"Mia": {"hp": 100, "class": "mage"},
	"Leo": {"hp": 80, "class": "knight"}
}

Chain the keys to reach a value inside. heroes["Mia"] is Mia's inner dictionary, and ["hp"] reads from it. Assignments work the same way:

print(heroes["Mia"]["hp"]) # 100
heroes["Leo"]["hp"] -= 30 # Leo takes damage
heroes["Mia"]["mana"] = 50 # adds a pair to Mia only
print(heroes["Mia"])
{ "hp": 100, "class": "mage", "mana": 50 }

To add a whole record, assign a dictionary to a new outer key: heroes["Ana"] = {"hp": 90, "class": "archer"}.

A missing key at either level is an error. When a record may be missing, call get() with an empty dictionary as the default, then get() again on the result:

print(heroes.get("Zed", {}).get("hp", 0)) # 0

To reach every inner value, loop over the outer keys and read from each inner dictionary:

var total_hp := 0
for hero in heroes:
	total_hp += heroes[hero]["hp"]
print(total_hp) # 150
challenge icon

Challenge

Easy

The nested dictionary inventory is given: each outer key is a department, each inner key an item, and each inner value the quantity in stock.

The program reads one line: lookups written as department/item, separated by commas. For each lookup, in order, print one line:

  • the lookup, a colon, a space and the quantity, when that department has that item
  • the lookup followed by : missing, when the department or the item does not exist

Then print Total inventory: followed by the sum of every quantity in every department.

For the input fruits/apples,meat/beef,fruits/kiwis,candy/gum, the output is:

fruits/apples: 12
meat/beef: 7
fruits/kiwis: missing
candy/gum: missing
Total inventory: 39

Try it yourself

extends Node

func _ready():
	var inventory := {
		"fruits": {"apples": 12, "bananas": 4},
		"meat": {"beef": 7, "chicken": 5},
		"dairy": {"milk": 9, "cheese": 2}
	}
	var lookups := OS.read_string_from_stdin().split(",")

	# Print the quantity of each lookup, or missing

	# Print the total of every quantity
	pass
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