Menu
CoddyTech

Dictionary as a Set

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

To turn an array into a set, loop over it and make each value a key. Repeated values land on the same key:

var reports := ["spam", "scam", "spam"]
var banned := {}
for word in reports:
	banned[word] = true
print(banned.keys()) # ["spam", "scam"]

To check whether a value is a member, use has() or the in operator. On a dictionary, both look at the keys, never at the values:

print(banned.has("scam")) # true
print("hello" in banned) # false
print("hello" not in banned) # true

An array also has has(), but it compares the value with the elements one by one. A dictionary finds a key directly, so a membership check on a set stays fast even with thousands of members.

A for loop over a set goes through its members, in the order they were added:

for word in banned:
	print(word) # spam, then scam
challenge icon

Challenge

Easy

You check guests at the door of a party. The program reads two lines of input:

  1. The guest list: names separated by spaces. Some names are written more than once.
  2. The people arriving: names separated by spaces.

Build the set guests from the guest list. Print how many different people are on the list, then one line per person arriving: NAME: welcome if they are on the list, or NAME: not on the list. For the input:

mia leo ana mia
mia sam ana

the output is:

Guests on the list: 3
mia: welcome
sam: not on the list
ana: welcome

Try it yourself

extends Node

func _ready():
	var guest_list := OS.read_string_from_stdin().split(" ", false)
	var arrivals := OS.read_string_from_stdin().split(" ", false)
	var guests := {}

	# Build the set of guests

	# Print the number of guests and check each arrival
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