01 / 20
{ }

Dictionary Creation
& Access

Learn to build Python dictionaries from scratch and access, update, and manage values using keys: the foundation of structured data.

Python

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

Mutable
You can add, change, or remove entries after creation.
Key-Based
Access values by their unique key, not by an index number.

Anatomy of a Key-Value Pair

student (dict) "name" : "Alice" "age" : 16 "grade" : "10th" Key (str) Value (str) Key (str) Value (int) Key (str) Value (str)

Why Use Dictionaries?

Dictionaries solve a core problem: connecting related pieces of data with meaningful labels instead of relying on numeric positions.

Fast Lookups
Finding a value by key is nearly instant, regardless of dictionary size.
Readable Code
student["name"] is far clearer than student[0].
Flexible
Values can be mixed types: strings, lists, nested dicts, and more.

Creating a Dictionary

# Method 1: Literal syntax student = { "name": "Alice", "age": 16, "grade": "10th" } # Method 2: dict() constructor student = dict(name="Alice", age=16, grade="10th") # Method 3: Empty dictionary empty = {} also_empty = dict()

Accessing Values by Key

student = {"name": "Alice", "age": 16} # Bracket notation print(student["name"]) # "Alice" # .get() method (safe access) print(student.get("age")) # 16 print(student.get("gpa", 0)) # 0 (default)
dict["key"]
Raises a KeyError if the key does not exist.
dict.get("key")
Returns None (or a default) if the key is missing. Safer.

Bracket vs .get()

dict["key"] Key exists? Yes Returns value No KeyError! Program crashes dict.get("key") Key exists? Yes Returns value No Returns None Program continues

Updating & Adding Entries

student = {"name": "Alice", "age": 16} # Update an existing value student["age"] = 17 # Add a brand-new key student["gpa"] = 3.8 print(student) # {"name": "Alice", "age": 17, "gpa": 3.8}

Removing Entries

student = {"name": "Alice", "age": 17, "gpa": 3.8} # del removes a specific key del student["gpa"] # .pop() removes and returns the value age = student.pop("age") print(age) # 17 # .clear() empties the entire dict student.clear() print(student) # {}
del dict[key]
Deletes the pair. Raises KeyError if missing.
.pop(key)
Removes and returns the value. Accepts an optional default.
.clear()
Empties the dictionary completely, leaving { }.

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

1
Identify your data. What pieces of information belong together? What label describes each piece?
2
Choose keys and values. Keys are the labels (strings). Values hold the data (any type).
3
Create the dictionary. Use { } with colon-separated pairs, each separated by commas.
4
Access values. Use dict["key"] or dict.get("key") to retrieve data.
5
Update as needed. Assign dict["key"] = new_value to modify or add entries.

Example 1: Building a Contact

# Create a contact dictionary contact = { "first": "Maya", "last": "Chen", "phone": "555-0142" } # Access the phone number print(contact["phone"]) # Output: 555-0142 # Add an email contact["email"] = "maya@example.com" print(contact) # {"first": "Maya", "last": "Chen", # "phone": "555-0142", "email": "maya@example.com"}

Example 2: Score Tracker

# Track game scores scores = {"Alice": 10, "Bob": 7} # Bob scores 3 more points scores["Bob"] = scores["Bob"] + 3 # Or equivalently: scores["Bob"] += 3 # New player joins scores["Carol"] = 0 # Safe check for missing player dan_score = scores.get("Dan", 0) print(dan_score) # 0 (default, no crash) print(scores) # {"Alice": 10, "Bob": 10, "Carol": 0}

Example 3: Nested Dictionaries

# A dict whose values are also dicts school = { "alice": {"grade": 10, "gpa": 3.8}, "bob": {"grade": 11, "gpa": 3.5} } # Access Bob's GPA (chain two brackets) print(school["bob"]["gpa"]) # Output: 3.5 # Update Alice's GPA school["alice"]["gpa"] = 3.9

Common Mistakes

✕ Using an Index
student[0] does not give you the first pair. Dictionaries use keys, not indices.
✕ Mutable Keys
Using a list as a key causes a TypeError. Keys must be immutable (str, int, tuple).
✕ Missing Key Crash
Accessing dict["missing"] raises a KeyError. Use .get() for safety.

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?