Python
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax and Data Types
-
Section 3: Collections
-
39: Set Operations: Union, Intersection, Difference
-
Section 4: Control Flow
-
Section 5: Functions
-
Section 6: Turtle Graphics and Early Practice Projects
-
Section 7: Working with Files and I/O
-
Section 8: Regular Expressions
-
Section 9: Object-Oriented Python
-
Section 10: Error Handling
-
Section 11: Modules and Packages
-
Section 12: Iterators, Generators, and Functional Tools
-
Section 13: Decorators and Metaprogramming
-
Section 14: Concurrency and Parallelism
-
Section 15: Working with Dates, Times, and Numbers
-
Section 16: Standard Library Deep Dive I: Data Structures
-
Section 17: Standard Library Deep Dive II: System and Introspection
-
Section 18: Standard Library Deep Dive III: Security and Encoding
-
Section 19: Standard Library Deep Dive IV: Text and Data Utilities
-
Section 20: Networking and Web Basics
-
Section 21: Working with Databases
-
Section 22: Testing and Quality
-
Section 23: Advanced Typing
-
Section 24: Context Managers and Resource Handling
-
Section 25: Text, Unicode, and Binary Data
-
Section 26: More Functional and Iteration Tools
-
Section 27: Data Validation and Configuration
-
Section 28: Working with Images and Media
-
Section 29: Property-Based and Documentation Testing
-
Section 30: Packaging and Deployment
-
Section 31: Performance and Internals
-
Section 32: Design Patterns in Python
-
Section 33: GUI Programming
-
Section 34: Security Basics
-
Section 35: Data Structures and Algorithms
-
Section 36: Practical Projects
-
Section 37: Capstone Projects
-
Section 38: Interview and Algorithm Practice
-
Section 39: Writing Idiomatic Python
40: Dictionaries: Creating and Accessing
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
albumwith 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.
There are no comments for now.