Menu
CoddyTech

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 3

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

Challenge

Easy

The program reads four lines of input:

  1. A player name
  2. A starting level (a whole number)
  3. A new level (a whole number)
  4. A new pair written as key:value, for example guild:Falcons

The dictionary player is already created with "name" and "level". Then:

  1. Update "level" with the new level
  2. Split the fourth input at : and add that pair to the dictionary (keep the value as text)
  3. 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
quiz iconTest yourself

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

All lessons in Fundamentals

Practice on your own: Online GDScript compiler