Historical Context & Motivation
Imagine you have a contact list on your phone. You don't look up a friend by saying "give me person number 47"—you search by their name and instantly get their phone number. This idea of pairing a lookup key with a stored value is one of the most powerful concepts in all of computer science. Long before Python existed, programmers needed a way to organize data so they could find it quickly without scanning through every item one by one.
Lists and arrays store items in numbered positions, which works great when you know the index. But what if you want to store a student's grade by their name, or look up the capital of a country? You need a data structure that maps one piece of information to another. This need gave rise to the hash map (also called a hash table), which Python implements as the dictionary.
.get() and .update(), making dictionaries even more flexible and developer-friendly.The core question this lesson addresses is straightforward: How do you create a dictionary in Python, and how do you access or change the values stored inside it? Understanding dictionaries unlocks the ability to model real-world relationships in your code—from student grades to game inventories to website data.
Core Principles & Definitions
A dictionary in Python (abbreviated dict) is an unordered collection of key-value pairs. Each key acts as a unique label that maps to exactly one value. You can think of it like a real-world dictionary: the word (key) maps to its definition (value). There are a few essential principles you need to know before writing your first dictionary.
Key-Value Pairs
key: value.Keys Must Be Unique
Keys Must Be Immutable
Values Can Be Anything
Fast Lookups — O(1)
Visual Explanation — Dictionary Structure
The diagram below shows how a Python dictionary organizes key-value pairs internally. On the left, you can see the keys—unique labels that point to their corresponding values on the right. The curly braces { } surround the whole structure, and each pair is separated by a comma.
Notice that the values are diverse: "Alice" is a string, 11 is an integer, 3.8 is a float, and ["Chess", "Code"] is a list. This flexibility is a major advantage of dictionaries—unlike a list where every element is accessed by a numeric index, here you access data with a meaningful, human-readable key.
How It Works — Creating Dictionaries
Python gives you several ways to create a dictionary. The most common approach uses curly brace literal syntax, but you can also use the built-in dict() constructor or start with an empty dictionary and add items one at a time. Let's look at each method and understand when to use it.
Method 1 — Curly Brace Literals
key: value pair is separated by commas. Keys and values are separated by a colon. The entire collection is wrapped in curly braces { }.For example, scores = {"math": 92, "english": 88, "science": 95} creates a dictionary with three subjects as keys and their scores as values. This is the most common and readable way to create a dictionary when you already know the data.
Method 2 — The dict() Constructor
dict(), keys are passed as keyword arguments (no quotes around them) and they must be valid Python identifiers. This only works when keys are simple strings.Method 3 — Start Empty, Add Later
{} or dict(), then add entries one at a time using bracket notation. This is useful when building a dictionary dynamically inside a loop.{} creates an empty dictionary, not an empty set. To create an empty set, you must use set(). This is one of the most common mistakes beginners make in Python.Accessing & Updating Values
Once you've created a dictionary, you need to know how to read values, update existing entries, and add new pairs. Python provides two primary ways to access values: bracket notation and the .get() method. Understanding the difference between them is essential.
[ ], safe reading with .get(), updating existing values, and adding new key-value pairs. Notice that adding and updating use the same syntax—Python decides based on whether the key already exists.| Operation | Syntax | Behavior if Key Missing |
|---|---|---|
| Read (bracket) | d[key] | Raises KeyError |
| Read (safe) | d.get(key, default) | Returns None or your chosen default |
| Update existing | d[key] = new_value | Creates a new entry instead |
| Add new | d[new_key] = value | Always creates the entry |
| Delete | del d[key] | Raises KeyError |
Worked Example — Building a Student Gradebook
Let's walk through a realistic scenario. You're building a simple gradebook program that stores a student's name and their scores in different subjects. We'll create the dictionary, access values, update a grade after a retest, and add a new subject.
gradebook = {"algebra": 85, "biology": 91, "history": 78}"biology".
bio_grade = gradebook["biology"]
print(bio_grade)91.get() prevents a crash.
chem_grade = gradebook.get("chemistry", "Not enrolled")
print(chem_grade)Not enrolled — No error, just the default value.gradebook["history"] = 88
print(gradebook){"algebra": 85, "biology": 91, "history": 88}gradebook["art"] = 94
print(gradebook){"algebra": 85, "biology": 91, "history": 88, "art": 94}in keyword to check if a key exists before using bracket notation: if "chemistry" in gradebook:. This is another way to avoid a KeyError without using .get().Dictionaries vs. Lists — When to Use Which
If you already know Python lists, you might wonder when to use a dictionary instead. Both store collections of data, but they're designed for very different purposes. The table below compares the two data structures across several key dimensions.
| Feature | List | Dictionary |
|---|---|---|
| Access Method | By numeric index: my_list[0] | By key: my_dict["name"] |
| Order | Ordered by position | Ordered by insertion (Python 3.7+) |
| Lookup Speed | O(n) — must scan through items to find a value | O(1) — jumps directly to the value via its key |
| Duplicates | Allows duplicate values | Keys must be unique; values can repeat |
| Best For | Ordered sequences of similar items (e.g., a list of temperatures) | Named data fields or lookups (e.g., student records, settings) |
Connection to Advanced Topics
The basics of dictionary creation and access are the foundation for many powerful Python techniques. As you progress, you'll encounter more advanced ways to work with dictionaries. The table below previews some of these topics and how they build on what you've learned today.
| What You Learned Today | What Comes Next |
|---|---|
Creating dictionaries with { } | Dictionary comprehensions: Build dicts in one line with {k: v for k, v in iterable} |
Accessing with d[key] and .get() | Iterating with loops: Use .keys(), .values(), and .items() to loop through dictionaries |
| Single-level key-value pairs | Nested dictionaries: Dictionaries inside dictionaries for complex data like JSON |
Manual default handling with .get() | defaultdict from the collections module: Automatically provides default values for missing keys |
Dictionaries are also the engine behind many real-world applications. Web APIs send data as JSON (JavaScript Object Notation), which maps almost directly to Python dictionaries. When you build web apps, games, or data science projects, you'll be working with dictionaries constantly. Mastering creation and access now sets you up for everything that follows.
Practice Problems
print statement output?
inventory = {"apples": 5, "bananas": 12, "oranges": 8}
a) print(inventory["bananas"])
b) print(inventory.get("grapes", 0))
c) print(inventory.get("apples", 0))word_counts and then processes the list words = ["hello", "world", "hello", "python", "world", "hello"]. After processing, word_counts should contain each unique word as a key and the number of times it appears as the value.settings = {"volume": 80, "brightness": 70}
backup = settings
settings["volume"] = 50
print(backup["volume"])
What does this print, and why? What would you do differently if you wanted backup to remain unchanged?Dictionary Creation & Access — Summary
A Python dictionary stores data as key-value pairs inside curly braces { }. Keys must be unique and immutable (strings, integers, or tuples), while values can be any Python type. You can create dictionaries using literal syntax, the dict() constructor, or by starting empty and adding items one at a time.
To read a value, use bracket notation d[key] for direct access (raises KeyError if missing) or the .get() method for safe access with a default fallback. To update an existing value or add a new entry, use the same d[key] = value syntax—Python creates the key if it's new or overwrites it if it exists. Dictionaries provide O(1) constant-time lookups, making them one of the most efficient and widely-used data structures in Python.