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
dragonAdd 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"]) # 85print() shows the whole array with every dictionary in it: [{ "type": "slime", "hp": 35 }, ...].
Challenge
EasyBuild 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.
- For each line, append a dictionary with the keys
"name"(the name) and"score"(the score as anint) to the arrayplayers. - Print the array.
- 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
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