Menu
CoddyTech

Merging Dictionaries

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

merge() adds every pair of another dictionary to the dictionary you call it on. Keys that are only in the other dictionary are added at the end:

var settings := {"volume": 5, "difficulty": "normal"}
var saved := {"difficulty": "hard", "subtitles": true}
settings.merge(saved)
print(settings)
{ "volume": 5, "difficulty": "normal", "subtitles": true }

"difficulty" is in both dictionaries, and merge() kept the value settings already had: by default, existing keys are not overwritten. Pass true as the second argument to let the other dictionary win:

var options := {"volume": 5, "difficulty": "normal"}
options.merge(saved, true)
print(options["difficulty"]) # hard

merge() changes the dictionary itself and returns nothing, so var result := a.merge(b) is an error. To keep both dictionaries as they are, use merged(). It takes the same arguments and returns a new dictionary:

var defaults := {"volume": 5, "difficulty": "normal"}
var choice := {"difficulty": "hard"}
var final_settings := defaults.merged(choice, true)
print(final_settings) # { "volume": 5, "difficulty": "hard" }
print(defaults) # { "volume": 5, "difficulty": "normal" }

When a key is in both dictionaries and you want to combine the values, for example add up two amounts, write the loop yourself:

var bag := {"gold": 10, "gems": 1}
var loot := {"gold": 5, "keys": 2}
for key in loot:
	bag[key] = bag.get(key, 0) + loot[key]
print(bag) # { "gold": 15, "gems": 1, "keys": 2 }
challenge icon

Challenge

Easy

A game update added new settings. The player's saved settings are read from one line of input, written as key=value pairs separated by commas (the line can be empty). The given code stores them in the dictionary saved.

Fill in the settings the save is missing: add to saved every pair of defaults whose key is not in it yet, without changing the values the player chose and without changing defaults. Then print saved, and print defaults on the next line.

For the input difficulty=hard,volume=8, the output is:

{ "difficulty": "hard", "volume": "8", "subtitles": "off", "language": "en" }
{ "difficulty": "normal", "volume": "5", "subtitles": "off", "language": "en" }

Try it yourself

extends Node

func _ready():
	var defaults := {"difficulty": "normal", "volume": "5", "subtitles": "off", "language": "en"}
	var saved := {}
	for pair in OS.read_string_from_stdin().split(",", false):
		var parts := pair.split("=")
		saved[parts[0]] = parts[1]

	# Add the missing defaults to saved, then print both dictionaries
	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