Hey there, young coders! ๐ Are you ready to learn something super cool and fun? Today, we'll learn about Python dictionaries and how they're like the doors in your favorite Roblox game! ๐ฎ
Inspired by Aaron Liu who shared this amazing game with me
What's a Python Dictionary? ๐
A Python dictionary is like a magical storage box ๐ that holds pairs of keys ๐ and values ๐. Imagine you're playing Roblox, and you find lots of colorful doors ๐ช๐. To open each door, you need the matching key. That's just how Python dictionaries work!
โญ Fun Fact:In Python, dictionaries are also called "dicts"!
How Do Dictionaries Work? ๐ค
Let's create a simple dictionary to store the keys for our Roblox doors. Here's our magical storage box:
door_keys = {}
It's empty right now, but let's add some keys ๐ and their matching door colors ๐ช:
door_keys = {
"red_door": "red_key",
"blue_door": "blue_key",
"green_door": "green_key"
}
Now, we have a dictionary with three doors and their matching keys. Let's see how to use it!
Opening the Doors ๐ช
To open a door, we just need to find the matching key in our dictionary. Let's try to open the red door:
key_for_red_door = door_keys["red_door"]
print("The key for the red door is:", key_for_red_door)
This will print:
The key for the red door is: red_key
๐ Congratulations! You just opened the red door using a Python dictionary!
Adding More Doors ๐๐ช
You can also add new doors to your magical storage box. Let's add a yellow door:
door_keys["yellow_door"] = "yellow_key"
Now our dictionary looks like this:
{
"red_door": "red_key",
"blue_door": "blue_key",
"green_door": "green_key",
"yellow_door": "yellow_key"
}
Let's Play with Our Dictionary! ๐ฎ
Want to make sure you have the right key for a door? Here's an easy trick:
door_to_check = "blue_door"
if door_to_check in door_keys:
print("We have the key for", door_to_check)
else:
print("Oops! We don't have the key for", door_to_check)
This will print:
We have the key for blue_door
Your Turn ๐
Python dictionaries are like magical storage boxes ๐ that hold pairs of keys ๐ and values ๐. They're perfect for organizing and finding things, just like the keys to open doors in Roblox!
Now you know how to create, use, and update Python dictionaries! ๐
Exercise 1: Update Dictionary
Given a dictionary student with the key name having the value "John Doe" and the key age having the value 25, write a Python script to add a new key-value pair, "grade" with the value "A-", and update the age to 26.
student = {
"name": "John Doe",
"age": 25
}
# Your code goes here
Exercise 2: Accessing Values
Consider the following dictionary of a book collection with the book titles as keys and the respective authors as values:
book_collection = {
"1984": "George Orwell",
"Brave New World": "Aldous Huxley",
"Fahrenheit 451": "Ray Bradbury"
}
# Your tasks:
# 1. Print the author of "1984".
# 2. Check if "The Handmaid's Tale" is in the collection and print an appropriate message whether it is or not.
Comments