Dictionaries: The Robot’s Secret Address Book
Learn how to store labeled data using Python dictionaries. Understand keys, values, lookups, and updating dictionary entries.
Welcome back, explorer! 📖
In our previous lesson, we learned about lists (backpacks) where items are stored in numbered slots (0, 1, 2…). But what if you want to look up information using words instead of numbers?
For example, if you want to find a superhero’s superpower, you shouldn’t have to guess that Sonic is in slot 1. You want to look up “Sonic” and get “Super Speed” directly!
In Python, we do this using a Dictionary!
What is a Dictionary? (The Secret Address Book)#
Think of a dictionary as an address book or a phone book.
- Key: The word or name you look up (like the contact name).
- Value: The secret information or number matching that key.
graph LR
subgraph Dictionary ["📖 superpowers = {...}"]
Key1["🔑 'Sonic'"] --> Value1["💬 'Super Speed'"]
Key2["🔑 'Mario'"] --> Value2["💬 'Super Jump'"]
Key3["🔑 'Luigi'"] --> Value3["💬 'High Jump'"]
end
In Python, we write a dictionary using curly brackets { } and pair keys and values with colons ::
superpowers = {
"Sonic": "Super Speed",
"Mario": "Super Jump",
"Luigi": "High Jump"
}pythonLooking Up Information (Opening the Book)#
To look up a value, you write the name of the dictionary followed by the key in square brackets [ ]:
print(superpowers["Sonic"]) # The robot looks up 'Sonic' and prints "Super Speed" ⚡pythonModifying Your Address Book (Adding and Deleting)#
Just like a real address book, you can add new contacts, update powers, or erase entries.
1. Adding or Updating an Entry#
To add a new hero, write the new key in brackets and set it equal to their power:
superpowers["Yoshi"] = "Eat anything"
print(superpowers) # Yoshi is now in our dictionary! 🦖pythonYou can use the exact same way to change Mario’s power if he gets a power-up:
superpowers["Mario"] = "Fireball Shoot"python2. Deleting an Entry (del)#
To erase a contact, use the del (delete) command:
del superpowers["Luigi"]
# Luigi is now erased from the address book! 💨pythonTry It Yourself! 🎮#
Open your Python editor and try managing a pet database:
pet_sounds = {
"Dog": "Woof",
"Cat": "Meow",
"Cow": "Moo"
}
# 1. Look up the Cat sound
print("The Cat says:", pet_sounds["Cat"])
# 2. Add a new pet!
pet_sounds["Sheep"] = "Baa"
# 3. Erase the Cow
del pet_sounds["Cow"]
# 4. Print the final database
print("Final Database:", pet_sounds)pythonRun the code to see if your database updates correctly!
Congratulations! You have completed the 10-part coding series. You now possess all the core building blocks of programming. You can talk to screens, store values, branch paths, loop routines, build functions, pack lists, draw art, get user input, roll random dice, and map dictionaries. You are ready to build your first game! 🚀🎮