Dictionary Creation
& Access
Learn to build Python dictionaries from scratch and access, update, and manage values using keys: the foundation of structured data.
What Is a Dictionary?
A Python dictionary is a collection that stores data as key-value pairs. Since Python 3.7, dictionaries remember the order of insertion. Think of it like a real dictionary: every word (key) maps to a definition (value).
Anatomy of a Key-Value Pair
Why Use Dictionaries?
Dictionaries solve a core problem: connecting related pieces of data with meaningful labels instead of relying on numeric positions.
Creating a Dictionary
Accessing Values by Key
Bracket vs .get()
Updating & Adding Entries
Removing Entries
Dictionary vs List
| Dictionary | List | |
|---|---|---|
| Access by | Key (string, int, tuple) | Index (integer position) |
| Syntax | { "k": "v" } | ["a", "b", "c"] |
| Order | Insertion order (3.7+) | Ordered by index |
| Duplicates | Keys must be unique | Duplicates allowed |
| Best for | Labeled, structured data | Sequential collections |
How to Apply Dictionaries
Example 1: Building a Contact
Example 2: Score Tracker
Example 3: Nested Dictionaries
Common Mistakes
Dictionary Operations Summary
| Operation | Syntax | Result |
|---|---|---|
| Create | {"k": "v"} | New dict |
| Read | dict["key"] | Value (or KeyError) |
| Safe Read | dict.get("key", d) | Value (or default d) |
| Add / Update | dict["key"] = val | Adds or overwrites |
| Delete | del dict["key"] | Removes pair |
| Pop | dict.pop("key") | Removes and returns |
| Check Key | "key" in dict | True / False |
| Length | len(dict) | Number of pairs |
Question 1 of 5
Which of the following correctly creates a Python dictionary with two key-value pairs?
Question 2 of 5
Given info = {"city": "Boston", "state": "MA"}, what does info.get("zip", "N/A") return?
Question 3 of 5
What happens when you run d = {"a": 1}; d["b"] = 2?
Question 4 of 5
Given data = {"x": {"y": 5}}, how do you access the value 5?
Question 5 of 5
Which of the following cannot be used as a dictionary key in Python?