Accessing, Creating, Updating

The full text of this chapter, to read or revisit. To practise, do the exercises.

▶ Do the exercises

Exercise 1 — Accessing Dictionary Values with Square Brackets

To access a value in a dictionary, use square brackets [] with the key inside. This is similar to how you access elements in a list, but instead of using an index number, you use the key.

aquachu = { "name": "Aquachu", "type": "water", "level": 15, "power": 75 } # Access values using keys print("Name:", aquachu["name"]) print("Type:", aquachu["type"]) print("Level:", aquachu["level"]) print("Power:", aquachu["power"])

The syntax is: dictionary_name[key] When you use the correct key, Python returns the corresponding value. Make sure the key exists in the dictionary, otherwise you'll get a KeyError!

Exercise 2 — Understanding KeyError

When you try to access a key that doesn't exist in a dictionary, Python raises a KeyError. This is an error that stops your program.

pyrochu = { "name": "Pyrochu", "type": "fire", "level": 18 } # This works fine print("Name:", pyrochu["name"]) # This will cause a KeyError! # Uncomment the line below to see the error # print("Power:", pyrochu["power"])

The KeyError occurs because "power" is not a key in the pyrochu dictionary. To avoid this error, you can: 1. Make sure the key exists before accessing it 2. Use the .get() method (we'll learn this next!)

Always check your keys!

KeyError is one of the most common errors when working with dictionaries. Double-check that your keys are spelled correctly and actually exist in the dictionary!

Exercise 3 — Correct Dictionary Access Syntax

Given the following dictionary, which is the correct way to access the "type" value?

florachu = { "name": "Florachu", "type": "plant", "level": 12 }
Options
• florachu["type"]
• florachu("type")
• florachu.type
• florachu{"type"}

Hint : Remember that dictionary access uses square brackets [] with the key inside as a string.

Exercise 4 — Safe Access with the .get() Method

The .get() method is a safer way to access dictionary values. Instead of raising a KeyError when the key doesn't exist, it returns None (or a default value you specify).

Syntax: - dictionary.get(key) - Returns the value or None if key doesn't exist - dictionary.get(key, default_value) - Returns the value or default_value if key doesn't exist

aquachu = { "name": "Aquachu", "type": "water", "level": 15 } # Using .get() with existing key print("Name:", aquachu.get("name")) # Using .get() with non-existing key (returns None) print("Power:", aquachu.get("power")) # Using .get() with default value print("Power with default:", aquachu.get("power", 0)) print("HP with default:", aquachu.get("hp", 100))

When to use .get() vs []

Personally, I use get() most of the time to avoid unexpected errors in my code but there are no hard rules.

Exercise 5 — Understanding .get() Return Values

What will the following code print?

codemon = {"name": "Pyrochu", "type": "fire"} result = codemon.get("level", 1) print(result)
Options
• 1
• None
• KeyError
• "level"

Hint : Think about what happens when .get() is called with a key that doesn't exist and a default value is provided.

Exercise 6 — Modifying Dictionary Values

You can change the value of an existing key by using assignment with square brackets. The syntax is the same as accessing, but you use the assignment operator = to set a new value.

aquachu = { "name": "Aquachu", "level": 10, "power": 50 } print("Before:", aquachu) # Update the level aquachu["level"] = 15 # Update the power aquachu["power"] = 75 print("After:", aquachu)

The syntax is: dictionary[existing_key] = new_value This replaces the old value with the new one (or creates the key if it doesn't exist).

Exercise 7 — Adding New Key-Value Pairs

Like I just said in the last exercise, you can add new key-value pairs to a dictionary using the same syntax as updating values. If the key doesn't exist, Python creates it automatically!

florachu = { "name": "Florachu", "type": "plant" } print("Original:", florachu) # Add new keys florachu["level"] = 12 florachu["power"] = 70 florachu["hp"] = 100 print("After adding keys:", florachu)

The syntax is: dictionary[new_key] = value Python doesn't differentiate between updating an existing key and creating a new one - it's the same operation! If the key exists, it updates; if it doesn't exist, it creates.

Dictionaries are dynamic

Unlike some other programming languages, Python dictionaries can grow and shrink dynamically. You can add as many key-value pairs as you need at any time!

Exercise 8 — Practice Accessing and Modifying

Complete the code to access the Codémon's type, update its level to 20, and add a new "hp" key with value 150.

Hint : Remember: use square brackets with the key name for both accessing and modifying/adding values.

Exercise 9 — Checking if a Key Exists

Before accessing a dictionary value with [], it's often useful to check if the key exists to avoid KeyError. You can use the in keyword for this.

aquachu = { "name": "Aquachu", "type": "water", "level": 15 } # Check if keys exist print("Has 'name'?", "name" in aquachu) print("Has 'power'?", "power" in aquachu) print("Has 'type'?", "type" in aquachu)aquachu = { "name": "Aquachu", "type": "water", "level": 15 } # Use with conditional if "power" in aquachu: print("Power:", aquachu["power"]) else: print("Power not found, setting default") aquachu["power"] = 50 print("Power:", aquachu["power"])

The syntax is: key in dictionary This returns True if the key exists, False otherwise. It's very useful in conditional statements to safely check before accessing.

Exercise 10 — Match Dictionary Access Methods

Match each dictionary operation with its correct description:

Items to match
• dict["key"]
• dict.get("key")
• dict["key"] = value
• "key" in dict
Definitions
• Access value, raises KeyError if key doesn't exist
• Access value, returns None if key doesn't exist
• Update existing key or create new key-value pair
• Check if key exists, returns True or False

Exercise 11 — Challenge: Level Up Your Codémon

Your Codémon just won a battle and needs to be updated! Use dictionary operations to manage its stats. 1. Print the Codémon's current name and level 2. Increase the level by 5 3. Increase the power by 20 4. Add a new key "wins" with the value 1 5. Add a new key "hp" with the value 120 6. Print the updated dictionary

Starter code
codemon = { "name": "Pyrochu", "type": "fire", "level": 10, "power": 50 } print("=== BEFORE BATTLE ===") # 1. Print current name and level print("\n=== UPDATING STATS ===") # 2. Increase level by 5 # 3. Increase power by 20 # 4. Add wins key with value 1 # 5. Add hp key with value 120 print("\n=== AFTER BATTLE ===") # 6. Print updated dictionary
Back to the course