Imagine you’re creating a character card for a game. The character has a name, attack, health, and class. How do you keep all of that together?
You could create multiple variables:
hero_name = "Arthur"
hero_attack = 15
hero_health = 100
hero_class = "Warrior"
But that’s inconvenient! What if there are many characters? You need something better.
🗂️ What Is a Dictionary?
A dictionary is like a box with labeled tabs. Each tab has a name (key), and the value sits behind it.
In a regular dictionary:
- Word (key) → Definition (value)
- “Dragon” → “A mythical creature that breathes fire”
In a Python dictionary:
- Key → Value
- "name" → "Arthur"
- "attack" → 15
🎮 Creating Your First Dictionary
A dictionary is created with curly braces { }:
hero = {
"name": "Arthur",
"attack": 15,
"health": 100
}
Syntax:
- Curly braces { }
- key: value pairs
- Separated by commas
- Keys are usually strings (in quotes)
📥 Reading Values from a Dictionary
Use square brackets with the key to retrieve a value:
hero = {
"name": "Arthur",
"attack": 15,
"health": 100
}
print(hero["name"]) # Arthur
print(hero["attack"]) # 15
print(hero["health"]) # 100
Important: Use exactly the same key you defined!
✏️ Changing Values
You can update any value in the dictionary:
hero = {"name": "Arthur", "health": 100}
print(f"Health: {hero['health']}") # 100
# Hero takes damage
hero["health"] = 80
print(f"Health after hit: {hero['health']}") # 80
# You can use arithmetic
hero["health"] = hero["health"] - 20 # Subtract 20
print(f"Health: {hero['health']}") # 60
# Shorthand
hero["health"] -= 15 # Another -15
print(f"Health: {hero['health']}") # 45
➕ Adding New Keys
Just assign a value to a new key:
hero = {
"name": "Arthur",
"health": 100
}
# Add new fields
hero["level"] = 1
hero["exp"] = 0
print(hero)
# {'name': 'Arthur', 'health': 100, 'level': 1, 'exp': 0}
🐲 Practical Example: Monster Card
dragon = {
"name": "🐲 Fire Dragon",
"attack": 25,
"health": 150,
"type": "fire"
}
print(f"Opponent: {dragon['name']}")
print(f"Attack: {dragon['attack']}")
print(f"Health: {dragon['health']}")
print(f"Type: {dragon['type']}")
# Dragon attacks the hero
hero_health = 100
damage = dragon["attack"]
hero_health -= damage
print(f"\n💥 Dragon attacked! Damage: {damage}")
print(f"Hero health: {hero_health}")
Output:
Opponent: 🐲 Fire Dragon
Attack: 25
Health: 150
Type: fire
💥 Dragon attacked! Damage: 25
Hero health: 75
📋 List of Dictionaries: A Collection of Objects
The most powerful pattern — you can create a list of dictionaries! Think of it as a deck of cards where each card is a separate dictionary:
creatures = [
{"name": "🐲 Dragon", "attack": 8, "health": 12},
{"name": "🧙 Mage", "attack": 6, "health": 8},
{"name": "⚔️ Knight", "attack": 5, "health": 10}
]
# Print all creatures
for creature in creatures:
print(f"{creature['name']} - ATK: {creature['attack']}, HP: {creature['health']}")
Output:
🐲 Dragon - ATK: 8, HP: 12
🧙 Mage - ATK: 6, HP: 8
⚔️ Knight - ATK: 5, HP: 10
🎯 Value Types in a Dictionary
A dictionary can hold any data types:
player = {
"name": "Player1", # string
"level": 5, # integer
"health": 100.5, # float
"is_alive": True, # boolean
"inventory": ["sword", "shield"] # list
}
print(f"Name: {player['name']}")
print(f"Level: {player['level']}")
print(f"Alive: {player['is_alive']}")
print(f"Inventory: {player['inventory']}")
⚠️ Common Mistakes
1. Wrong Key
hero = {"name": "Arthur", "health": 100}
# ❌ ERROR: KeyError
print(hero["Name"]) # Capital N — that's a different key!
# ✅ CORRECT
print(hero["name"]) # Exactly as defined
2. Forgot Quotes Around the Key
# ❌ ERROR
hero = {name: "Arthur"} # name without quotes
# ✅ CORRECT
hero = {"name": "Arthur"}
3. Missing Commas Between Pairs
# ❌ ERROR: missing comma
hero = {
"name": "Arthur"
"health": 100
}
# ✅ CORRECT
hero = {
"name": "Arthur",
"health": 100
}
📊 Comparison: List vs Dictionary
| List | Dictionary |
|---|---|
| Access by position (index) | Access by key (name) |
names[0] → first element |
hero["name"] → value of name |
Square brackets [ ] |
Curly braces { } |
| Order matters | Order doesn’t matter (Python 3.7+ preserves insertion order) |
| For homogeneous data | For object attributes |
When to use a list:
- A collection of similar things
- planets = ["Mars", "Venus", "Jupiter"]
- Order is important
When to use a dictionary:
- Describing a single object
- hero = {"name": "Arthur", "level": 5}
- Named fields are needed
🎯 Summary
| Action | Code | Result |
|---|---|---|
| Create a dictionary | hero = {"name": "Arthur"} |
New dictionary |
| Get a value | hero["name"] |
"Arthur" |
| Change a value | hero["health"] = 80 |
health is now 80 |
| Add a key | hero["level"] = 1 |
New field level |
| Damage a character | hero["health"] -= 10 |
health decreases by 10 |
Remember:
- ✅ A dictionary is made of key: value pairs
- ✅ Use curly braces { }
- ✅ Access values via dictionary["key"]
- ✅ You can modify and add fields
- ✅ Perfect for storing object attributes
💬 Comments (0)
No comments yet
Be the first to share your opinion about this article!