Modifying Dictionaries
Part of the Fundamentals section of Coddy's GDScript journey. Lesson 79 of 92.
To change a value, assign to its key with square brackets. If the key is new, the pair is added at the end of the dictionary:
var player := {"name": "Mia", "hp": 100}
player["hp"] = 80 # updates the value of "hp"
player["level"] = 2 # adds a new pair
print(player)The output is:
{ "name": "Mia", "hp": 80, "level": 2 }You can also update a value from its old value, like a variable:
player["level"] += 1 # level is now 3To remove a pair, call erase() with its key. It returns true when the key was removed and false when the key was not there. A missing key is not an error:
print(player.erase("hp")) # true
print(player.erase("hp")) # false
print(player) # { "name": "Mia", "level": 3 }erase() does not return the removed value. If you need it, read it before you erase the key.
Challenge
EasyThe program reads four lines of input:
- A player name
- A starting level (a whole number)
- A new level (a whole number)
- A new pair written as
key:value, for exampleguild:Falcons
The dictionary player is already created with "name" and "level". Then:
- Update
"level"with the new level - Split the fourth input at
:and add that pair to the dictionary (keep the value as text) - Save the value of
"name"in a variable, then erase the key"name"
Print the saved name on the first line and the dictionary on the second line. For the inputs Mia, 4, 5 and guild:Falcons, the output is:
Mia
{ "level": 5, "guild": "Falcons" }Try it yourself
extends Node
func _ready():
var player_name := OS.read_string_from_stdin()
var level := int(OS.read_string_from_stdin())
var new_level := int(OS.read_string_from_stdin())
var pair := OS.read_string_from_stdin()
var player := {"name": player_name, "level": level}
# 1. Update the level
# 2. Add the pair from the fourth input
# 3. Save the name, then erase it
# 4. Print the saved name and the dictionary
pass
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 1
Arithmetic OperatorsInteger DivisionModulo OperatorArithmetic ShortcutsRecap - Simple MathComparison Operators10Functions
Declare a FunctionArgumentsReturnReturn TypesRecap - Sigma FunctionRecap - Validation FunctionDefault Values5Operators Part 2
Logical Operators Part 1Logical Operators Part 2Recap - Simple LogicLogical Operators Part 3Ternary Operator9Loops
For LoopWhile LoopBreakContinueRecap - FactorialThe Range FunctionNested LoopRecap - Dynamic Input12Arrays Basics
Declaring an ArrayAccessing Array ElementsModifying ArraysArray MethodsRecap - Product ArrayRecap - Reversed ArrayTyped Arrays15Dictionaries
Creating DictionariesAccessing ValuesModifying DictionariesDictionary MethodsIterating Over DictionariesRecap - Inventory DictionaryPractice on your own: Online GDScript compiler