Menu
CoddyTech

Accessing Values

Part of the Fundamentals section of Coddy's GDScript journey. Lesson 78 of 92.

To read a value, put its key in square brackets after the dictionary name:

var player := {"name": "Mia", "hp": 100}
print(player["name"]) # Mia
print(player["hp"]) # 100

The key must match exactly, including capital letters: "Name" and "name" are different keys.

Reading a key that is not in the dictionary is an error, and the program stops at that line:

print(player["mana"]) # Error: the key "mana" does not exist

When a key may be missing, use get(). It returns the value of the key, or the default value you pass as the second argument when the key is missing:

print(player.get("hp", 0)) # 100
print(player.get("mana", 0)) # 0

Without a default, get() returns null for a missing key, and print() shows it as <null>.

challenge icon

Challenge

Easy

The program reads four lines of input:

  1. An item name
  2. A price (a decimal number)
  3. A stock count (a whole number)
  4. A key to look up

Create a dictionary called item with these pairs:

  • "name" mapped to the item name
  • "price" mapped to the price
  • "stock" mapped to the stock count

Then print the value of the key from the fourth input. If the key is not in the dictionary, print Not found.

For the inputs Potion, 2.5, 15 and price, the output is:

2.5

For the inputs Bow, 30.75, 7 and color, the output is:

Not found

Try it yourself

extends Node

func _ready():
	var item_name := OS.read_string_from_stdin()
	var price := float(OS.read_string_from_stdin())
	var stock := int(OS.read_string_from_stdin())
	var key := OS.read_string_from_stdin()

	# Create the item dictionary here

	# Print the value of key, or Not found
	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