๐Ÿ“ Python

Dictionaries in Python: Storing Data as Key-Value Pairs ๐Ÿ“–

P
Author
PyLand Team
๐Ÿ“…
Published
30.03.2026
โฑ๏ธ
Reading time
4 min
๐Ÿ‘๏ธ
Views
391
๐ŸŒฑ
Level
Beginner

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):

  • key is the key to find;
  • default is 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

Your reaction to the article

๐Ÿ’ฌ Comments (0)

๐Ÿ” Sign in to leave a comment
๐Ÿšช Login
๐Ÿ’ญ

No comments yet

Be the first to share your opinion about this article!

๐Ÿ”— Similar

Similar articles

Continue learning with these materials

๐Ÿ“

Lists and Dictionaries in Python

Problem: Want to store 100 students โ†’ 100 variables? Solution: collections.

๐Ÿ“… 30.03.2026 ๐Ÿ‘๏ธ 386
๐Ÿ“

What is an ORM

ORM (Object-Relational Mapping) is a technology that lets you work with a database through Python...

๐Ÿ“… 30.06.2026 ๐Ÿ‘๏ธ 362
๐Ÿ“

JSON: Persisting Data

Goal: Learn to save and load data in JSON format.

๐Ÿ“… 03.04.2026 ๐Ÿ‘๏ธ 466