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.

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.

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.

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.

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.

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) % 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
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".

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.

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"])
Common dictionary record patterns in Python
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"}}

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
Step 1 โ€” Define the Record SchemaDecide 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
Step 2 โ€” Create the RecordsBuild 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
Step 3 โ€” Calculate Total Value per ProductFor 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
Step 4 โ€” Sum the Total Inventory ValueUse 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.

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.

Comparing Python data structures for record modeling
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
โœฆ 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.

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.

Dictionary records vs. class instances
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

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.

Practice Problems

PROBLEM 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?
PROBLEM 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?
PROBLEM 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.
PROBLEM 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.
PROBLEM 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.

Lesson 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