Menu
CoddyTech

Arrays of Dictionaries

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

When you have many records with the same fields, store them in an array of dictionaries: each element is one record.

var enemies := [
	{"type": "slime", "hp": 30},
	{"type": "orc", "hp": 80},
	{"type": "dragon", "hp": 500}
]

An index picks the record and a key picks the field: enemies[1]["type"] is "orc". A for loop gives you one dictionary per pass:

for enemy in enemies:
	if enemy["hp"] >= 80:
		print(enemy["type"])
orc
dragon

Add a record with append(). To change a field of every record, assign through the loop variable. Like arrays, dictionaries are shared, not copied, so enemy is the dictionary inside the array and the change stays there:

enemies.append({"type": "bat", "hp": 10})
for enemy in enemies:
	enemy["hp"] += 5
print(enemies[3]) # { "type": "bat", "hp": 15 }

To find a record by one of its fields, loop and compare. Start with null, so you can tell when nothing matched:

var found = null
for enemy in enemies:
	if enemy["type"] == "orc":
		found = enemy
if found == null:
	print("No orc")
else:
	print(found["hp"]) # 85

print() shows the whole array with every dictionary in it: [{ "type": "slime", "hp": 35 }, ...].

challenge icon

Challenge

Easy

Build a leaderboard. The program reads a whole number n, then n lines, each with a player name and a score separated by a comma, like Mia,95.

  1. For each line, append a dictionary with the keys "name" (the name) and "score" (the score as an int) to the array players.
  2. Print the array.
  3. Print Best: , the name of the player with the highest score and the score in parentheses. If two players share the highest score, print the first one.

For the inputs 3, Mia,95, Leo,80 and Ana,97, the output is:

[{ "name": "Mia", "score": 95 }, { "name": "Leo", "score": 80 }, { "name": "Ana", "score": 97 }]
Best: Ana (97)

Try it yourself

extends Node

func _ready():
	var n := int(OS.read_string_from_stdin())
	var players := []

	# Read the n players into the array

	# Print the array and the best player
	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