Computer Programming 1 (Python) • Core Data Structures

Modeling with Dictionaries — I can model a simple "record" (e.g., student, product) as a dictionary with consistent keys.

Learn how Python dictionaries let you bundle related data into a single, organized structure.

A Python coding terminal with a program flow and laptop.
Inside this lesson 10 sections 5 questions 7 figures

SECTION 1

Historical Context & Motivation

Long before Python existed, programmers struggled with a fundamental question: how do you keep related pieces of information together? Imagine you are building a school roster. You might store each student's name in one list, their grade in another, and their student ID in yet another. That approach works — until you accidentally delete an entry from one list and not the others. Suddenly your data is out of sync and your program produces wrong results.

The idea of grouping related data under named fields — called a record — has roots stretching back to the earliest days of computing. Languages like COBOL (1959) introduced formal record types for business data, and the concept evolved through C's struct and eventually into Python's flexible dictionary. Dictionaries give you the power to model real-world entities — students, products, game characters — in a single, self-describing bundle.

1959 • COBOL Records

COBOL introduced formal record types to group related fields like employee name, salary, and department into a single structure for business applications.

1972 • C Structs

The C programming language offered struct, letting programmers bundle named fields together with strict data types — a lightweight record.

1991 • Python Is Born

Guido van Rossum released Python 0.9.0 with built-in dictionaries (key-value mappings), making record-style modeling accessible from day one.

2010s • JSON & APIs

The explosion of web APIs and JSON (JavaScript Object Notation) made dictionary-like structures the universal format for exchanging data between apps and servers.

The central question this lesson addresses is straightforward: How can you represent a real-world entity — like a student or a product — as a single Python dictionary with consistent, predictable keys? Mastering this skill is the first step toward building databases, web applications, and data-driven programs.

SECTION 2

Core Principles & Definitions

Before you start building dictionaries, you need to understand a handful of foundational ideas. A Python dictionary (often shortened to dict) is a collection of key-value pairs. Each key acts like a label, and each value is the data associated with that label. When you use the same set of keys across multiple dictionaries, you are modeling a record — turning a real-world thing into structured data your program can process.

1

Key-Value Pair

The basic unit of a dictionary. The key is a unique label (usually a string), and the value is the data it points to. Example: "name": "Alice"
2

Consistent Keys

When every dictionary representing the same type of entity uses the same set of keys, your code becomes predictable and much easier to debug. Think of it like every student form having the same blank fields.
3

Record

A record is one entity's complete data — all its fields filled in. A single dictionary with consistent keys represents one record, like one row in a spreadsheet.
4

Mutability

Dictionaries are mutable, meaning you can add, change, or remove key-value pairs after creation. This lets you update a student's grade or a product's price on the fly.
✦

KEY TAKEAWAY

Think of a dictionary as a student ID card. Every ID card has the same fields printed on it — Name, Grade, Student ID — but each card is filled in with different information. The fields are the keys, and the information written in is the values. Using the same fields on every card means anyone can read any card without confusion — that is what consistent keys give you in code.

SECTION 3

Visual Explanation

The diagram below shows how a real-world student is turned into a Python dictionary. On the left, you see the concept of a student with their attributes. On the right, that same information is captured as key-value pairs inside curly braces. Notice how each key is a string label and each value holds the actual data.

From Real World → Python Dictionary🎓 Student EntityName: Alice ChenAge: 16Grade: 11GPA: 3.8Email: alice@school.eduPython Dictionary"name":"Alice Chen""age":16"grade":11"gpa":3.8"email":"alice@school.edu"Keys (cyan) → Values (pink)Each attribute maps to exactly one key-value pair
The left panel shows a real-world student entity with five attributes. Each attribute becomes a key (shown in cyan) paired with its corresponding value (shown in pink) inside the Python dictionary on the right.

In Python code, this dictionary would look like:

💡

Python Code

student = {"name": "Alice Chen", "age": 16, "grade": 11, "gpa": 3.8, "email": "alice@school.edu"}

To access any value, you use the key inside square brackets: student["name"] returns "Alice Chen". This is why dictionaries are sometimes called associative arrays — they associate a key with a value, just like a real dictionary associates a word with its definition.

SECTION 4

How Dictionaries Work Under the Hood

You don't need to memorize the internal mechanics to use dictionaries well, but understanding the basics will help you write better code. Python dictionaries use a technique called hashing. When you store a key-value pair, Python runs the key through a hash function — a formula that converts the key into a number. That number tells Python exactly where to store (and later find) the value in memory.

HASH LOOKUP

index=hash(key)index = hash(key) % table_size

hash(key) converts the key into a large integer. The % (modulo) operator maps that integer to a valid slot in the table. This is why lookup by key is essentially instant — Python jumps straight to the right slot.

Because of hashing, looking up a value by its key is an O(1) operation on average — it takes the same amount of time whether your dictionary has 10 entries or 10 million. Compare that to a list, where finding a specific value might require checking every element (an O(n) operation). This speed advantage is one reason dictionaries are so popular for modeling records.

TIME COMPLEXITY COMPARISON

Dictlookup:O(1)vs.Listsearch:O(n)Dict lookup: O(1) vs. List search: O(n)

O(1) means constant time — the operation takes roughly the same time regardless of how many items exist. O(n) means the time grows linearly with the number of items n.

⚠

Why Keys Must Be Immutable

Because Python hashes the key, the key's value must never change after creation. Strings, integers, and tuples are all immutable (unchangeable) and can be used as keys. Lists are mutable (changeable) and cannot be used as keys. If a key could change, its hash would change too, and Python would lose track of where the value is stored.

The practical takeaway is simple: use strings as your dictionary keys when modeling records. Strings are descriptive, immutable, and easy to read — exactly what you need for field names like "name", "price", or "email".

SECTION 5

Common Record Patterns & Structure

When you model records with dictionaries, you'll encounter several common patterns. The key insight is that every dictionary of the same type should use the exact same keys. This consistency makes it possible to loop through a list of records, access the same field on each one, and process them uniformly. Below is a diagram showing how multiple student records share a common structure.

List of Student Records — Consistent KeysSCHEMA (Keys)"name""age""gpa"applied to eachRecord 0"name": "Alice Chen""age": 16"gpa": 3.8{"name": "Alice Chen", "age": 16, "gpa": 3.8}Record 1"name": "Bob Ramirez""age": 17"gpa": 3.5{"name": "Bob Ramirez", "age": 17, "gpa": 3.5}Record 2"name": "Chloe Park""age": 15"gpa": 3.9{"name": "Chloe Park", "age": 15, "gpa": 3.9}All three records use identical keys: "name", "age", "gpa"
Three student records stored in a list. Each dictionary uses the same three keys — "name", "age", and "gpa" — ensuring consistency across all records.

In code, these three records would live inside a list of dictionaries:

💡

Python Code — List of Records

students = [ {"name": "Alice Chen", "age": 16, "gpa": 3.8}, {"name": "Bob Ramirez", "age": 17, "gpa": 3.5}, {"name": "Chloe Park", "age": 15, "gpa": 3.9}, ]

Because every record uses the same keys, you can write a simple loop that works for any number of students:

ℹ

Looping Through Records

for s in students: print(s["name"], "has a GPA of", s["gpa"])
PatternDescriptionExample
Single RecordOne dictionary representing one entityproduct = {"name": "Laptop", "price": 999.99}
List of RecordsA list where each element is a dictionary with the same keysproducts = [{...}, {...}, {...}]
Nested RecordA dictionary whose value is another dictionarystudent = {"name": "Alice", "address": {"city": "Portland", "state": "OR"}}

Common dictionary record patterns in Python

SECTION 6

Worked Example — Building a Product Catalog

Let's build a small product catalog for an online store. We need to store each product's name, price, quantity in stock, and category. Then we'll calculate the total inventory value.

Product Catalog — Total Inventory Value

  1. 1

    Step 1 — Define the Record Schema

    Decide what keys every product dictionary will have. We choose four consistent keys: "name" (string), "price" (float), "qty" (integer), and "category" (string).
    Schema: {"name": str, "price": float, "qty": int, "category": str}
  2. 2

    Step 2 — Create the Records

    Build a list of dictionaries, each following the schema: catalog = [ {"name": "Wireless Mouse", "price": 25.99, "qty": 150, "category": "Electronics"}, {"name": "Notebook", "price": 4.50, "qty": 500, "category": "Office"}, {"name": "USB-C Cable", "price": 12.00, "qty": 300, "category": "Electronics"}, ]
    3 product records created with consistent keys
  3. 3

    Step 3 — Calculate Total Value per Product

    For each product, multiply price × qty to get the inventory value of that product: for product in catalog: value = product["price"] * product["qty"] print(product["name"], "→ $" + str(value)) This outputs: Wireless Mouse → $3898.5, Notebook → $2250.0, USB-C Cable → $3600.0.
    Values: $3898.50, $2250.00, $3600.00
  4. 4

    Step 4 — Sum the Total Inventory Value

    Use a variable to accumulate the total: total = 0 for product in catalog: total += product["price"] * product["qty"] print("Total inventory value: $" + str(total))
    Total inventory value: $9748.50
💡

WHY THIS WORKS

Because every product dictionary has the same keys, the loop in Step 3 can confidently access product["price"] and product["qty"] without worrying that a key might be missing. Consistent keys make your loops safe and your code predictable.

SECTION 7

Dictionaries vs. Other Approaches

Dictionaries aren't the only way to store structured data in Python. You might wonder why you can't just use a list or a tuple. The table below compares the three approaches so you can see why dictionaries shine when modeling records.

FeatureListTupleDictionary
Access by name?No — access by index only (e.g., student[0])No — access by index only (e.g., student[0])Yes — access by key (e.g., student["name"])
Self-documenting?No — you must remember what index 0 meansNo — same problem as listsYes — key names describe the data
Mutable?Yes — can change valuesNo — immutable after creationYes — can update, add, or remove pairs
OrderingOrdered by positionOrdered by positionInsertion-ordered (Python 3.7+)
Best for records?Poor — fragile and unclearOkay for read-only dataExcellent — clear, flexible, and fast

Comparing Python data structures for record modeling

✦

KEY TAKEAWAY

Using a list to store a record is like labeling your school locker with a number instead of your name. You can find your stuff — but only if you remember that locker 0 is 'name,' locker 1 is 'age,' and so on. A dictionary labels each compartment, so anyone reading your code can instantly tell what each piece of data represents.

SECTION 8

Connection to Classes & Databases

Modeling records with dictionaries is your stepping stone to more powerful concepts. In a later course you will learn about classes (object-oriented programming), which let you define a formal blueprint for a record, including not just data but also methods — functions that operate on that data. Dictionaries and classes solve similar problems, but classes add structure and reusability.

FeatureDictionary RecordClass Instance
Data storageKey-value pairs inside {}Attributes defined in __init__
Behavior (methods)Not built in — use separate functionsMethods are defined inside the class
Key enforcementVoluntary — programmer must be disciplinedEnforced — __init__ defines required attributes
When to useQuick prototyping, config data, JSON handlingLarger programs, when behavior is needed

Dictionary records vs. class instances

Beyond classes, the record concept maps directly to database rows. When you eventually work with databases (SQL or NoSQL), each row in a table is essentially a record with consistent columns — the same idea as consistent dictionary keys. The skills you're building now with dictionaries will transfer directly to those advanced tools.

ℹ

JSON Connection

When you use a web API (like a weather service or a game leaderboard), the data almost always arrives in JSON format — which looks nearly identical to a Python dictionary. Learning to model records now prepares you to work with real-world APIs using import json.

SECTION 9

Practice Problems

Question 1: CONCEPTUAL

Explain in your own words why using consistent keys across multiple dictionary records is important. What could go wrong if one record used the key "student_name" while another used "name" for the same data?
Show answer
Consistent keys allow your code to loop through a list of records and access the same field on each one without errors. If one record uses "student_name" and another uses "name", a loop that accesses record["name"] will crash with a KeyError when it hits the record that uses the different key. Consistent keys make your code predictable, debuggable, and safe to iterate over.

Question 2: BASIC CALCULATION

Given the dictionary book = {"title": "1984", "author": "Orwell", "pages": 328, "price": 9.99}, write a Python expression that calculates the price per page. What value does it produce?
Show answer
The expression is book["price"] / book["pages"]. This divides 9.99 by 328, which gives approximately 0.03045 (about 3 cents per page). You access each value by its key — "price" and "pages" — so the code is self-documenting and easy to understand.

Question 3: INTERMEDIATE

You have a list of movie records: movies = [{"title": "Inception", "year": 2010, "rating": 8.8}, {"title": "Interstellar", "year": 2014, "rating": 8.6}, {"title": "The Matrix", "year": 1999, "rating": 8.7}]. Write a loop that prints only the titles of movies with a rating above 8.7.
Show answer
The solution uses a for loop with an if condition: for movie in movies: if movie["rating"] > 8.7: print(movie["title"]). This prints only "Inception" because its rating (8.8) is the only one that exceeds 8.7. The consistent keys "rating" and "title" let the loop work on every record without modification.

Question 4: APPLIED

You're building a gradebook. Design a dictionary schema for a student record that includes their name, a list of test scores, and their letter grade. Then write a function average_score(student) that takes one student dictionary and returns the average of their test scores.
Show answer
A good schema would be: {"name": str, "scores": list of int/float, "grade": str}. An example record: {"name": "Dana", "scores": [88, 92, 75, 95], "grade": "B+"}. The function would be: def average_score(student): return sum(student["scores"]) / len(student["scores"]). For Dana, this returns (88 + 92 + 75 + 95) / 4 = 87.5. Note that "scores" is a list stored as a dictionary value — values can be any data type, including other collections.

Question 5: CRITICAL THINKING

A teammate writes this code to store employee records, but some records are missing the "department" key: employees = [{"name": "Eli", "department": "Engineering"}, {"name": "Fay"}]. Later, a loop does for e in employees: print(e["department"]). What error will occur? Propose two different strategies to prevent this error while still handling records that might lack a department.
Show answer
A KeyError will occur when the loop reaches Fay's record because it has no "department" key. Strategy 1: Always include the key with a default value — {"name": "Fay", "department": "Unassigned"}. This enforces consistent keys. Strategy 2: Use the .get() method, which returns a default value instead of crashing — e.get("department", "N/A"). Strategy 1 is better for data integrity because it forces every record to have the same structure. Strategy 2 is a defensive coding technique that protects against messy real-world data.

SUMMARY

Lesson Summary

Summary

A Python dictionary stores data as key-value pairs, making it the ideal structure for modeling a record — a single real-world entity like a student, product, or movie. By using consistent keys across every dictionary of the same type, you ensure that loops, functions, and data processing logic work reliably on every record. Keys should be immutable (strings are the best choice), and values can be any data type — strings, numbers, lists, or even other dictionaries.

Dictionaries outperform lists and tuples for record modeling because they are self-documenting (the key tells you what the value represents) and offer O(1) lookup speed. A list of dictionaries is the go-to pattern for managing collections of records. This skill is the foundation for working with classes, databases, and JSON-based web APIs in future courses.

Varsity Tutors • Computer Programming 1 (Python) • Modeling with Dictionaries