Menu
CoddyTech

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) # true

size() 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()) # true

has() and in look only at the keys, never at the values: player.has("Mia") is false.

challenge icon

Challenge

Easy

The 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:

  1. Each key, one per line
  2. ---
  3. Each value, one per line
  4. ---
  5. The number of pairs
  6. ---
  7. true or false: whether the dictionary is empty
  8. ---
  9. true or false: 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
---
true

Try 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
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