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!
๐ก๏ธ The get() Method: A Value Without KeyError
Square brackets work when a key must exist. If the key is missing, the program stops with KeyError:
status_penalties = {
"ONLINE": 0,
"DEGRADED": 15,
"OFFLINE": 30
}
print(status_penalties["UNKNOWN"]) # KeyError
The get() method lets you provide a fallback value:
penalty = status_penalties.get("UNKNOWN", 20)
print(penalty) # 20
In dictionary.get(key, default):
keyis the key to find;defaultis returned when that key is missing.
For an existing key, get() returns the stored value:
print(status_penalties.get("DEGRADED", 20)) # 15
Without a fallback value, a missing key returns None:
print(status_penalties.get("UNKNOWN")) # None
Use square brackets when a missing key means the data is incorrect. Use get() when the program already knows which fallback value to use.
โ๏ธ 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!