person = {"name": "Alice", "age": 25, "city": "NYC"}
# Using square bracketsprint(person["name"]) # Alice# Using get() - safer (no error if key missing)print(person.get("age")) # 25print(person.get("email")) # Noneprint(person.get("email", "N/A")) # N/A (default)
Alice
25
None
N/A
get() vs Square Brackets
dict["key"] - Raises KeyError if key doesn't exist. dict.get("key") - Returns None if key doesn't exist (no error!). dict.get("key", default) - Returns default value if key doesn't exist. Best practice: Use get() when you're not sure if the key exists.
Dictionary Key Rules
Keys must be immutable (hashable): strings, numbers, tuples work. Lists and dicts cannot be keys.
Keys must be unique: duplicate keys overwrite previous values.
Values can be anything: strings, numbers, lists, even other dictionaries!
Lab Exercise 1: Dictionary Basics
Beginner
Instructions
Practice creating and accessing dictionary values.
Your Task
Create a dictionary book with keys: "title", "author", "year", "pages". Print the title and use get() to print a non-existent "isbn" key with default "Unknown".
Code Editor
Output
Click "Run Code" to see output...
Checkpoint: Dict Basics Complete!
You can create and access dictionaries. Let's explore methods!
Dictionary Methods
Dictionaries have powerful built-in methods for working with keys and values.
Keys, Values, and Items
methods.pyPython
person = {"name": "Alice", "age": 25, "city": "NYC"}
# Get all keysprint(list(person.keys())) # ['name', 'age', 'city']# Get all valuesprint(list(person.values())) # ['Alice', 25, 'NYC']# Get key-value pairs as tuplesprint(list(person.items())) # [('name', 'Alice'), ...]# Check if key existsprint("name"in person) # Trueprint("email"in person) # False
person = {"name": "Alice", "age": 25, "city": "NYC"}
# del - Delete by keydel person["city"]
print(person) # {'name': 'Alice', 'age': 25}# pop() - Remove and return value
age = person.pop("age")
print(f"Removed age: {age}")
# pop() with default (no error if missing)
email = person.pop("email", "Not found")
print(f"Email: {email}")
# popitem() - Remove last item (Python 3.7+)
person["job"] = "Engineer"
last = person.popitem()
print(f"Removed: {last}")
{'name': 'Alice', 'age': 25}
Removed age: 25
Email: Not found
Removed: ('job', 'Engineer')
Lab Exercise 3: CRUD Operations
Intermediate
Instructions
Practice adding, updating, and deleting dictionary entries.
Your Task
Start with user = {"username": "wizard01"}. Add "email" and "level" keys. Update level to 10. Remove email using pop(). Print the final dictionary.
Code Editor
Output
Click "Run Code" to see output...
Checkpoint: CRUD Complete!
You can modify dictionaries. Let's learn iteration!
Iterating Through Dictionaries
Loop through dictionaries to process each key-value pair.
Different Ways to Iterate
iteration.pyPython
scores = {"Alice": 95, "Bob": 87, "Charlie": 92}
# Iterate over keys (default)for name in scores:
print(name)
# Iterate over valuesfor score in scores.values():
print(score)
# Iterate over key-value pairs (MOST COMMON)for name, score in scores.items():
print(f"{name}: {score}")
Alice
Bob
Charlie
95
87
92
Alice: 95
Bob: 87
Charlie: 92
items() is Your Friend
for key, value in dict.items(): is the most Pythonic way to iterate when you need both keys and values. The tuple unpacking makes your code clean and readable!
Dictionary Comprehension
dict_comp.pyPython
# Create dict from lists
names = ["Alice", "Bob", "Charlie"]
scores = [95, 87, 92]
grades = {name: score for name, score inzip(names, scores)}
print(grades)
# Transform values
doubled = {k: v * 2for k, v in grades.items()}
print(doubled)
# Filter with condition
passing = {k: v for k, v in grades.items() if v >= 90}
print(passing)
Given prices = {"apple": 1.50, "banana": 0.75, "orange": 2.00}, loop through and print each item with its price, then calculate the total price if you bought one of each.
Code Editor
Output
Click "Run Code" to see output...
Checkpoint: Iteration Complete!
You can loop through dictionaries. Let's explore nested dicts!
Nested Dictionaries
Dictionaries can contain other dictionaries, creating complex data structures perfect for representing real-world data.
# Update nested value
students["alice"]["grades"]["english"] = 90# Loop through nested structurefor student_id, info in students.items():
print(f"{info['name']}:")
for subject, grade in info["grades"].items():
print(f" {subject}: {grade}")
Alice Smith:
math: 95
science: 92
english: 90
Bob Jones:
math: 88
science: 85
JSON Connection
Nested dictionaries are exactly how JSON data is represented in Python! When you work with APIs or config files, you'll use this pattern constantly. Python's json module converts JSON ↔ dict seamlessly.
Lab Exercise 5: Nested Dictionaries
Advanced
Instructions
Practice working with nested dictionary structures.
Your Task
Create a nested dictionary for a "config" with keys "database" (containing "host" and "port") and "app" (containing "name" and "version"). Print the database host.
Code Editor
Output
Click "Run Code" to see output...
Checkpoint: Nested Dicts Complete!
You can work with complex data. Time for the summary!