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) # trueAn 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 scamChallenge
EasyYou check guests at the door of a party. The program reads two lines of input:
- The guest list: names separated by spaces. Some names are written more than once.
- 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 anathe output is:
Guests on the list: 3
mia: welcome
sam: not on the list
ana: welcomeTry 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
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