Dictionaries: Store Data with Key-Value Pairs

Introduction

In this chapter, you will learn Python dictionaries, a powerful structure for organizing related data using key-value pairs. Dictionaries are widely used in real projects for user profiles, settings, configurations, and API responses. Once you understand dictionaries, your code can model real-world data much more naturally.

Prerequisites

  • Python 3.10+ installed
  • Basic understanding of variables, lists, tuples, and loops
  • Ability to run .py files in terminal or IDE

What Is a Dictionary

A dictionary stores data as key: value pairs.

Think of it like:

  • A real dictionary: word -> meaning
  • A contact card: field name -> field value
python
# Create a dictionary
student = {
    "name": "Emma",
    "age": 10,
    "score": 95
}
 
# Print full dictionary
print(student)

1) Access Values by Key

Use keys to read values.

python
# Student profile dictionary
student = {"name": "Emma", "age": 10, "score": 95}
 
# Access values
print(student["name"])   # Emma
print(student["score"])  # 95

Safer access with .get():

python
# Access existing key
print(student.get("age"))  # 10
 
# Access missing key safely
print(student.get("grade", "N/A"))  # N/A

Tip

Best Practice

Use .get() when a key might be missing, so your code stays stable.

2) Add and Update Data

Dictionaries are mutable, so you can add or modify entries.

python
# Start dictionary
profile = {"name": "Tom", "age": 11}
 
# Add new key-value pair
profile["city"] = "Boston"
 
# Update existing value
profile["age"] = 12
 
# Print result
print(profile)

3) Remove Data

Common ways to remove entries:

  • pop(key) remove by key and return value
  • del dict[key] delete by key
  • clear() remove all entries
python
# Start dictionary
settings = {"theme": "dark", "font_size": 14, "lang": "en"}
 
# Remove one item and capture value
removed_lang = settings.pop("lang")
print(removed_lang)  # en
 
# Delete one key
del settings["font_size"]
 
# Print remaining entries
print(settings)

4) Loop Through a Dictionary

You can iterate keys, values, or both.

python
# Example dictionary
product = {"name": "Keyboard", "price": 49.9, "stock": 120}
 
# Loop through keys
for key in product:
    print(key)
 
# Loop through values
for value in product.values():
    print(value)
 
# Loop through key-value pairs
for key, value in product.items():
    print(f"{key}: {value}")

5) Real Mini Example: Student Score Manager

This mini project stores student names and scores in a dictionary.

python
# Create score dictionary
scores = {
    "Liam": 88,
    "Olivia": 93,
    "Noah": 85
}
 
# Add a new student
scores["Emma"] = 96
 
# Update an existing score
scores["Liam"] = 90
 
# Print score report
print("=== Student Scores ===")
for name, score in scores.items():
    print(f"{name}: {score}")

This pattern appears in dashboards, reports, and backend data handling.

6) Dictionary + List Combination

In practice, you often use a list of dictionaries.

python
# List of student dictionaries
students = [
    {"name": "Liam", "score": 88},
    {"name": "Emma", "score": 96},
    {"name": "Noah", "score": 85}
]
 
# Print each student card
for student in students:
    print(f"{student['name']} -> {student['score']}")

Warning

Dictionary keys must be unique.
If you assign the same key again, the old value is overwritten.

Common Beginner Mistakes

Mistake 1: Accessing Missing Keys Directly

data["missing_key"] raises KeyError. Use .get() when uncertain.

Mistake 2: Assuming Dictionary Keeps Input Order in Older Python

In modern Python (3.7+), insertion order is preserved. In much older versions, behavior can differ.

Mistake 3: Using Mutable Objects as Keys

Keys must be hashable. Lists and dictionaries cannot be keys.

Surprise Practice Challenge

Build a tiny "Class Contact Book":

  1. Create a dictionary where key is student name and value is phone number
  2. Let user add one new contact
  3. Let user search one contact by name
  4. Print all contacts in name: phone format
  5. If search target is missing, print a friendly message

If you finish this, you already understand dictionary CRUD basics used in real systems.

FAQ

When should I use a dictionary instead of a list?

Use a dictionary when you need fast lookup by a meaningful key (like name, id, or config field).

Can dictionary values be different data types?

Yes. Values can be strings, numbers, lists, dictionaries, booleans, and more.

How do I merge two dictionaries?

Use dict_a | dict_b in modern Python, or dict_a.update(dict_b) if in-place update is fine.

Is dictionary lookup fast?

Yes. Average-time key lookup is very efficient, which is one reason dictionaries are heavily used.