Skip to Content
Course content

40: Dictionaries: Creating and Accessing

Click on the "Edit" button in the top corner of the screen to edit your slide content.

I was thinking about how to store some data for a small RPG project I'm tinkering with. At first, I thought a list would be fine for a player's stats. Let's see how that looks in practice.

player = ["Kaelen", 12, 85, "Warrior"]
print(player[2]) # I think this is health... right?

The "Wait, Which Index Was That?" Problem

The code works, and it prints 85, but I immediately hate it. If I come back to this code in three weeks, or if I hand it to you, neither of us will remember if index 2 is health, mana, or the number of potions in the bag. Relying on the position of a value is a recipe for bugs, especially once the list grows. I need a way to label my data.

This is exactly why Python has dictionaries. Instead of an ordered list, a dictionary is a map of keys to values. Let me rewrite that player object using curly braces {}.

player = {
    "name": "Kaelen",
    "level": 12,
    "health": 85,
    "class": "Warrior"
}

Now, the data is self-documenting. The string "health" is the key, and 85 is the value. It's a lot more intuitive.

Pulling Data Out by Name

Accessing the data is pretty straightforward. Instead of using a number in the square brackets, I just use the key name. I'll try to print the player's class:

print(player["class"]) 
# Output: Warrior

That's much cleaner. I don't have to count indices; I just ask for the "class". However, I'm curious about what happens if I ask for something that isn't there. Let's say I want to check the player's "mana", but since they are a Warrior, I never added a mana key to the dictionary.

print(player["mana"])

And there it is: KeyError: 'mana'. Python doesn't just return None or a blank space; it crashes the program. In a real game, a missing stat shouldn't crash the entire engine. I need a safer way to probe the dictionary.

Handling Missing Keys Gracefully

I remember there's a method called .get() specifically for this. The difference is that .get() returns None if the key is missing instead of raising an error. Let's test it.

mana_value = player.get("mana")
print(mana_value) 
# Output: None

That's better, but None might still cause issues if I try to do math with it (like subtracting damage from mana). The cool thing about .get() is that I can provide a second argument—a default value—to use if the key is missing.

# If "mana" isn't found, just assume it's 0
mana_value = player.get("mana", 0)
print(f"Mana level: {mana_value}")
# Output: Mana level: 0

Now the code is robust. I can check for any stat, and if it's not defined for that specific character, I have a sensible fallback. This pattern is a lifesaver when dealing with data from APIs or user input where you can't be 100% sure every field will be present.




📋 Practical Task

The Vintage Vinyl Record Catalog

You are building a small inventory system for a record store. You need to track a specific album's details using a dictionary.

  • Create a dictionary named album with the following keys: "title", "artist", and "year". Fill them with any album of your choice.
  • Print the "artist" of the album directly using square bracket notation.
  • The record store sometimes tracks the "condition" of the vinyl (e.g., "Mint" or "Good"), but not every record has this info. Use the .get() method to retrieve the "condition". If the key doesn't exist, it should return the default string "Unknown".
  • Print the result of that condition check to the console.
Rating
0 0

There are no comments for now.

to be the first to leave a comment.