Welcome back, Pythonistas! ๐ For the last two days, weโve been using indices like 0, 1, and 2 to grab items out of our lists and tuples. But letโs be realโif youโre building an RPG game and want to find a character's "stamina", nobody wants to guess whether that's stored at index 4 or index 7.
Today, we are throwing numerical indices out the window and upgrading to custom labels. Imagine a massive chest of drawers where you get to write the labels on the outside yourself.
Enter Dictionaries! ๐ท๏ธ๐
๐ What is a Dictionary?
In Python, a Dictionary is a collection of key-value pairs. Instead of looking up items by a number, you look them up using a unique word (the Key) to get the data attached to it (the Value).
To make a dictionary, we use curly braces {}, and we separate keys and values with a colon :
# Creating our character's stat sheet ๐ฎ
character = {
"name": "Anya",
"role": "Mage",
"level": 14,
"is_premium": True
}
print(character)
๐ Reading data with Custom Labels
To pull data out, you use the exact same square bracket setup we used for lists, but instead of a number, you pass in the exact string key:
# Checking Anya's role
print(character["role"]) # Prints: Mage
# Checking Anya's level
print(character["level"]) # Prints: 14
โ ๏ธ Tantrum Alert: Python keys are case-sensitive! If you try to look up character["Role"] with a capital R, Python will throw a KeyError and pretend it has never seen that data in its life.
๐ ๏ธ Modifying the Chest of Drawers
Dictionaries are completely mutable (flexible). You can change values, add new drawers, or rip drawers out completely.
# 1. Updating a value (Anya leveled up! ๐)
character["level"] = 15
# 2. Adding a brand new key-value pair
character["weapon"] = "Crystal Staff"
# 3. Deleting a key-value pair ๐๏ธ
del character["is_premium"]
print(character)
# Output: {'name': 'Anya', 'role': 'Mage', 'level': 15, 'weapon': 'Crystal Staff'}
๐ Today's Challenge ๐
Create a dictionary called my_car with the keys: brand, model, and year.
Print out the model of your car.
Update the year to a newer one (or change it to a hovercar from the future ๐).
Add a new key called color and give it a value.
Drop your custom dictionary in the comments below! Tomorrow, we are finishing our core data structures by looking at Setsโthe ultimate bouncers of the Python world! ๐๏ธ
Top comments (0)