SECTION 1
Historical Context & Motivation
Imagine you have a contacts list on your phone. You don't scroll through every single entry counting "contact #1, contact #2, contact #3" until you find someone. Instead, you search by name and instantly get their phone number. This idea — looking something up by a meaningful label rather than a position number — is one of the oldest and most powerful ideas in computer science. It's the core principle behind dictionaries in Python.
In earlier programming, data was stored almost exclusively in arrays and lists, which rely on numeric indexes. As programs grew more complex — managing user accounts, product catalogs, and configuration settings — developers needed a way to associate keys with values directly. The data structure that solved this problem has appeared under many names across decades of computing history.
1953 • Hash Tables Invented
1960s • Associative Arrays Emerge
1991 • Python Is Born
2017 • Python 3.7 — Ordered Dicts
So the central question dictionaries answer is: How can we store data so that we can find any piece of it almost instantly, using a meaningful name rather than remembering a position number? Python's dict is the answer, and it is one of the most-used data structures in real-world Python code.
SECTION 2
Core Principles & Definitions
A dictionary in Python is a collection of key-value pairs. Each key acts as a unique label, and each value is the data associated with that label. You create a dictionary with curly braces {} and separate each key from its value with a colon. Before diving into code, let's establish the foundational ideas that make dictionaries work.
Key-Value Pairs
key: value inside curly braces.Unique Keys
Mutable Structure
Fast Lookup
Key Restrictions
KEY TAKEAWAY
SECTION 3
Visual Explanation — Inside a Dictionary
The diagram below illustrates the structure of a Python dictionary that stores information about a student. On the left, you see the keys, and on the right, the values each key maps to. Arrows show which value belongs to which key. Notice that the keys are strings, but the values can be different types — a string, an integer, and a float.
In the diagram, notice three important things. First, each key is a string enclosed in quotes. Second, the values are of mixed types — a string, an integer, and a float — which is perfectly valid in Python. Third, the arrows go one way: you use a key to find its value, not the other way around. If you want to find which key has the value "Alice", you'd need to search through all the values, which is slower than a key lookup.
SECTION 4
How It Works — Creating, Reading, and Updating
Creating a Dictionary
There are two main ways to create a dictionary. The most common is literal syntax — you write curly braces with key-value pairs separated by commas. You can also create an empty dictionary and add pairs later. Here are both approaches:
LITERAL SYNTAX
Curly braces {} enclose the dictionary. Each key: value pair is separated by a comma. Keys are usually strings or numbers.
EMPTY DICTIONARY
Both create an empty dictionary with zero key-value pairs. You can add entries afterward using bracket notation.
Reading a Value (Key Lookup)
To read a value from a dictionary, you use bracket notation by placing the key inside square brackets after the dictionary name. This is called a key lookup. If the key doesn't exist, Python raises a KeyError. You can avoid this by using the .get() method, which returns None (or a default you specify) if the key is missing.
KEY LOOKUP
Returns the value associated with "key". Raises KeyError if the key is not found.
Updating and Adding Values
Updating a value uses the exact same bracket notation as reading, but combined with an assignment operator. If the key already exists, its value is overwritten. If the key doesn't exist yet, a brand-new key-value pair is added to the dictionary. This dual behavior — update or insert — is one of the most convenient features of dictionaries.
UPDATE / ADD
If "key" exists, the value is replaced. If it does not exist, a new pair is created.
SECTION 5
Common Dictionary Operations
Beyond creating, reading, and updating, Python dictionaries come with several built-in operations that make them even more powerful. The diagram below shows a dictionary going through a sequence of common operations — from creation, through lookups and updates, to deletion and membership checks.
"english" was deleted, "math" was updated, and "art" was added.| Operation | Syntax | What It Does |
|---|---|---|
| Create | d = {"a": 1, "b": 2} | Builds a new dictionary with initial key-value pairs |
| Read (bracket) | d["a"] | Returns the value for key "a"; raises KeyError if missing |
| Read (safe) | d.get("a", default) | Returns the value or a default if the key is missing |
| Update / Add | d["a"] = 99 | Changes the value for existing key or adds a new key-value pair |
| Delete | del d["a"] | Removes the key-value pair entirely from the dictionary |
| Membership | "a" in d | Returns True if the key exists, False otherwise |
| Length | len(d) | Returns the number of key-value pairs in the dictionary |
Quick reference for essential dictionary operations
SECTION 6
Worked Example — Building a Grade Tracker
Let's walk through a realistic scenario. You're building a small program to track quiz scores for a class. You need to create a dictionary of student scores, look up a specific student's score, update a score after a regrade, and add a new student who just joined.
Grade Tracker — Step by Step
- 1
Step 1 — Create the Dictionary
Start by creating a dictionary calledquiz_scoreswith three students and their scores. Use string names as keys and integer scores as values.quiz_scores = {"Maya": 85, "Jordan": 92, "Sam": 78} - 2
Step 2 — Read a Value Using Key Lookup
To check Jordan's score, use bracket notation with the key"Jordan". Python searches the dictionary for this key and returns the associated value.print(quiz_scores["Jordan"]) # Output: 92 - 3
Step 3 — Use .get() for Safe Lookup
Suppose you want to check a student named "Alex" who might not be in the dictionary yet. Using bracket notation would crash the program with a KeyError. Instead, use the.get()method with a default value of0.print(quiz_scores.get("Alex", 0)) # Output: 0 (no crash) - 4
Step 4 — Update an Existing Score
Sam's quiz was regraded and their new score is 83. Use bracket notation with assignment to overwrite the old value. Since the key"Sam"already exists, the old value (78) is replaced.quiz_scores["Sam"] = 83 # Dict is now {"Maya": 85, "Jordan": 92, "Sam": 83} - 5
Step 5 — Add a New Student
A new student named "Alex" has joined and scored 91 on the quiz. Use the same bracket-assignment syntax. Since"Alex"is not yet a key, Python creates a brand-new key-value pair.quiz_scores["Alex"] = 91 # Dict: {"Maya": 85, "Jordan": 92, "Sam": 83, "Alex": 91} - 6
Step 6 — Verify the Final Dictionary
Print the dictionary and its length to confirm all changes were applied correctly.print(quiz_scores) # {"Maya": 85, "Jordan": 92, "Sam": 83, "Alex": 91}print(len(quiz_scores)) # 4
Common Mistake
d["key"] (reading/updating a dictionary) with my_list[0] (accessing a list by index). Both use square brackets, but dictionaries use keys (like strings) while lists use integer positions. Mixing these up will cause a KeyError or TypeError.SECTION 7
Dictionaries vs. Lists — When to Use Each
You already know how to use lists to store ordered collections of data. So when should you reach for a dictionary instead? The key difference is how you access elements. Lists are position-based (you access item #0, #1, #2), while dictionaries are key-based (you access items by name). Each has strengths and trade-offs.
| Feature | List | Dictionary |
|---|---|---|
| Access method | By integer index: lst[0] | By key: d["name"] |
| Order | Always ordered by position | Preserves insertion order (Python 3.7+) |
| Duplicates | Allows duplicate values | Keys must be unique; values can repeat |
| Lookup speed | Searching for a value is slow for large lists | Looking up by key is very fast, even for huge dictionaries |
| Best used for | Ordered sequences — scores, steps, items in a queue | Labeled data — user profiles, settings, word counts |
| Syntax | [10, 20, 30] | {"a": 10, "b": 20} |
Lists vs. Dictionaries at a glance
KEY TAKEAWAY
SECTION 8
Connection to Advanced Concepts
The dictionary basics you've learned here are the foundation for several powerful techniques you'll encounter as you advance in Python. Understanding key-value pairs now prepares you for working with more complex data structures, file formats, and even web development. Here's a preview of where dictionaries lead.
| What You Know Now | Where It Leads |
|---|---|
| Simple key-value pairs with strings and numbers | Nested dictionaries — values that are themselves dictionaries, creating multi-level data structures |
Manual creation with {} | Dictionary comprehensions — building dictionaries in a single expressive line, similar to list comprehensions |
Using .get() for safe access | defaultdict and Counter — specialized dictionary types from Python's collections module that handle missing keys automatically |
| Storing data in Python objects | JSON (JavaScript Object Notation) — the most popular data format for web APIs, which maps directly to Python dictionaries |
| Key lookup for single values | Databases and ORM models — real-world database records are essentially rows of key-value pairs, with column names as keys |
From basics to advanced applications
If you've ever used a web API (like getting weather data or game stats), the data you received was almost certainly structured as nested dictionaries. Mastering the basics of creating, reading, and updating dictionaries is the essential first step toward working with real-world data in Python.
SECTION 9
Practice Problems
Question 1: CONCEPTUAL
Show answer
info[0] might give you the student's name, but only if you remember that index 0 stores the name. A dictionary uses descriptive keys: info["name"] clearly states what data you're retrieving. For student information, a dictionary is better because the data isn't naturally sequential — it's a collection of labeled attributes. Using keys like "name", "age", and "school" makes the code self-documenting and easier to read.Question 2: BASIC CALCULATION
prices = {"apple": 1.20, "banana": 0.50, "cherry": 2.00}, write a single Python expression that retrieves the price of a banana. Then write a statement that changes the price of an apple to 1.50.Show answer
prices["banana"], which returns 0.50. To update the apple price, use: prices["apple"] = 1.50. This works because bracket notation with assignment overwrites the existing value associated with "apple". The key already exists, so Python replaces 1.20 with 1.50 rather than creating a duplicate entry.Question 3: INTERMEDIATE
inventory = {"pencils": 50, "erasers": 30}. Write code that: (a) adds a new item "notebooks" with a quantity of 20, (b) increases the pencil count by 10 (without hardcoding 60), and (c) safely checks for "pens" and prints its quantity or "Not in stock" if it's missing.Show answer
inventory["notebooks"] = 20 — since "notebooks" doesn't exist yet, Python adds it. (b) inventory["pencils"] = inventory["pencils"] + 10 or equivalently inventory["pencils"] += 10. This reads the current value (50), adds 10, and stores 60 back. (c) print(inventory.get("pens", "Not in stock")). The .get() method returns the default string "Not in stock" because "pens" is not a key in the dictionary, avoiding a KeyError.Question 4: APPLIED
"the cat sat on the mat", write Python code that builds a dictionary where each key is a word and each value is the number of times it appears. Use a for loop, .split(), and the .get() method.Show answer
sentence = "the cat sat on the mat" → counts = {} → for word in sentence.split(): → counts[word] = counts.get(word, 0) + 1. The .get(word, 0) returns the current count if the word is already in the dictionary, or 0 if it's new. Adding 1 gives the updated count. The result is {"the": 2, "cat": 1, "sat": 1, "on": 1, "mat": 1}. This pattern — using .get() to initialize missing keys — is one of the most common dictionary idioms in Python.Question 5: CRITICAL THINKING
data = {"id": 1, "name": "Laptop", "id": 2}
What value does data["id"] return? Based on this, write a rule for how Python handles duplicate keys when creating a dictionary, and suggest how your classmate should fix their code.Show answer
"id" appears twice during dictionary creation, Python processes the pairs in order and the second value (2) overwrites the first (1). So data["id"] returns 2, and len(data) is 2, not 3. The rule is: when duplicate keys appear in a dictionary literal, the last value assigned to that key wins. To fix this, the classmate should use unique keys — for example, {"id_1": 1, "name": "Laptop", "id_2": 2} — or reconsider the data model, perhaps using a list of dictionaries if they need to store multiple items: [{"id": 1, "name": "Laptop"}, {"id": 2, "name": "Phone"}].SUMMARY
Lesson Summary
Summary
A Python dictionary is a collection of key-value pairs enclosed in curly braces. You create a dictionary with {"key": value} syntax and read values using bracket notation (d["key"]) or the safer .get() method. You update existing values and add new pairs using the same d["key"] = value assignment syntax. Keys must be unique and immutable (strings, numbers, or tuples), while values can be any type.
Dictionaries differ from lists because they use meaningful keys rather than numeric positions, and their hashing mechanism makes lookups extremely fast regardless of size. Use "key" in d to check membership, del d["key"] to delete entries, and len(d) to count pairs. Mastering these basics opens the door to nested dictionaries, JSON data, and the many advanced dictionary tools in Python's standard library.