Dictionary Methods
Part of the Fundamentals section of Coddy's GDScript journey. Lesson 80 of 92.
Dictionaries have methods that tell you what they contain.
keys() returns an array of the keys, and values() returns an array of the values, in the order of the pairs:
var player := {"name": "Mia", "hp": 100, "level": 3}
print(player.keys()) # ["name", "hp", "level"]
print(player.values()) # ["Mia", 100, 3]has() checks whether a key exists. The in operator does the same check:
print(player.has("hp")) # true
print(player.has("mana")) # false
print("level" in player) # truesize() returns the number of pairs, and is_empty() checks whether there are none:
print(player.size()) # 3
print(player.is_empty()) # false
var bag := {}
print(bag.is_empty()) # truehas() and in look only at the keys, never at the values: player.has("Mia") is false.
Challenge
EasyThe program reads two lines of input: a list of pairs written as key:value and separated by commas, and a key to check. The given code already fills the dictionary info from the first line.
Print, in this order:
- Each key, one per line
---- Each value, one per line
---- The number of pairs
---trueorfalse: whether the dictionary is empty---trueorfalse: whether the key from the second input exists
For the inputs name:Mia,hp:100,class:Mage and hp, the output is:
name
hp
class
---
Mia
100
Mage
---
3
---
false
---
trueTry it yourself
extends Node
func _ready():
var text := OS.read_string_from_stdin()
var key := OS.read_string_from_stdin()
var info := {}
for pair in text.split(","):
var parts := pair.split(":")
info[parts[0]] = parts[1]
# Print the keys, the values, the size, is_empty and has(key)
# with --- between the parts
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