COMPUTER PROGRAMMING 1 (PYTHON) • CORE DATA STRUCTURES

Dictionary Basics — I can create dictionaries and use key lookup to read and update values.

Learn how Python dictionaries let you store and retrieve data instantly using meaningful keys instead of numbered positions.

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
IBM researcher Hans Peter Luhn proposed hash tables, a technique for mapping keys to memory locations, enabling near-instant data retrieval.
1960s
Associative Arrays Emerge
Languages like SNOBOL introduced associative arrays, allowing programmers to use strings as keys instead of just numbers.
1991
Python Is Born
Guido van Rossum released Python 0.9.0, which included the dict type as a built-in data structure from day one, making key-value storage a first-class citizen of the language.
2017
Python 3.7 — Ordered Dicts
Starting with Python 3.7, dictionaries officially preserve insertion order, meaning key-value pairs stay in the order you added them.

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.

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.

1

Key-Value Pairs

Every entry in a dictionary consists of a key (the label) and a value (the data). Written as key: value inside curly braces.
2

Unique Keys

Each key in a dictionary must be unique. If you assign a value to an existing key, the old value is replaced. Two different keys can store the same value, but no two entries can share a key.
3

Mutable Structure

Dictionaries are mutable, meaning you can add, change, or remove key-value pairs after the dictionary is created. This makes them flexible for storing data that changes over time.
4

Fast Lookup

Python uses a technique called hashing behind the scenes. This lets you look up any key in roughly the same amount of time, regardless of how large the dictionary is.
5

Key Restrictions

Keys must be of an immutable type — strings, numbers, and tuples are valid keys. Lists and other dictionaries cannot be used as keys because they can change.
✦ KEY TAKEAWAY
Think of a Python dictionary like a real-world dictionary book. In a book dictionary, you look up a word (the key) and find its definition (the value). You don't need to know that "python" is the 47,832nd word — you jump straight to the "P" section and find it. Python dictionaries work the same way: you access data by its key, not by its position.

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.

A dictionary with three key-value pairs. The cyan boxes are keys (strings), and the pink boxes are values (which can be different types). Purple arrows show the mapping from each key to its value.

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.

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
my_dict = {"key1": value1, "key2": value2, "key3": value3}
Curly braces {} enclose the dictionary. Each key: value pair is separated by a comma. Keys are usually strings or numbers.
EMPTY DICTIONARY
my_dict = {} or my_dict = dict()
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
value = my_dict["key"]
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
my_dict["key"] = new_value
If "key" exists, the value is replaced. If it does not exist, a new pair is created.

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.

A flowchart showing six common dictionary operations applied in sequence. The final state at the bottom reflects all changes: "english" was deleted, "math" was updated, and "art" was added.
Quick reference for essential dictionary operations
OperationSyntaxWhat It Does
Created = {"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 / Addd["a"] = 99Changes the value for existing key or adds a new key-value pair
Deletedel d["a"]Removes the key-value pair entirely from the dictionary
Membership"a" in dReturns True if the key exists, False otherwise
Lengthlen(d)Returns the number of key-value pairs in the dictionary

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 DictionaryStart by creating a dictionary called quiz_scores with 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 LookupTo 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 LookupSuppose 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 of 0.
print(quiz_scores.get("Alex", 0)) # Output: 0 (no crash)
4
Step 4 — Update an Existing ScoreSam'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 StudentA 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 DictionaryPrint 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
A frequent beginner error is confusing 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.

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.

Lists vs. Dictionaries at a glance
FeatureListDictionary
Access methodBy integer index: lst[0]By key: d["name"]
OrderAlways ordered by positionPreserves insertion order (Python 3.7+)
DuplicatesAllows duplicate valuesKeys must be unique; values can repeat
Lookup speedSearching for a value is slow for large listsLooking up by key is very fast, even for huge dictionaries
Best used forOrdered sequences — scores, steps, items in a queueLabeled data — user profiles, settings, word counts
Syntax[10, 20, 30]{"a": 10, "b": 20}
✦ KEY TAKEAWAY
Use a list when order matters and you'll access items by position — like a playlist where song #1, #2, #3 matters. Use a dictionary when you want to label your data and look things up by name — like a contacts app where you search by a person's name, not their position in the list.

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.

From basics to advanced applications
What You Know NowWhere It Leads
Simple key-value pairs with strings and numbersNested 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 accessdefaultdict and Counter — specialized dictionary types from Python's collections module that handle missing keys automatically
Storing data in Python objectsJSON (JavaScript Object Notation) — the most popular data format for web APIs, which maps directly to Python dictionaries
Key lookup for single valuesDatabases and ORM models — real-world database records are essentially rows of key-value pairs, with column names as keys

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.

Practice Problems

PROBLEM 1 — CONCEPTUAL
Explain the difference between how you access data in a list versus a dictionary. Why would you choose a dictionary over a list to store a student's personal information (name, age, school)?
PROBLEM 2 — BASIC CALCULATION
Given the dictionary 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.
PROBLEM 3 — INTERMEDIATE
You have the dictionary 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.
PROBLEM 4 — APPLIED
You're writing a program that counts how many times each word appears in a sentence. Given the sentence "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.
PROBLEM 5 — CRITICAL THINKING
A classmate writes this code and expects the dictionary to store three entries, but it only ends up with two. Explain why. 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.

Lesson 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.

Varsity Tutors • Computer Programming 1 (Python) • Dictionary Basics