← Back to Python Chapter 6: Dictionaries
0% Complete

Dictionaries: Key-Value Storage

A dictionary (dict) is a collection of key-value pairs. Unlike lists that use numeric indices, dictionaries let you access values using custom keys.

Creating Dictionaries

creating_dicts.py Python
# Empty dictionary empty = {} # Dictionary with data person = { "name": "Alice", "age": 25, "city": "New York" } # Using dict() constructor scores = dict(math=95, science=87, english=92) print(person) print(scores)
{'name': 'Alice', 'age': 25, 'city': 'New York'} {'math': 95, 'science': 87, 'english': 92}

Accessing Values

accessing.py Python
person = {"name": "Alice", "age": 25, "city": "NYC"} # Using square brackets print(person["name"]) # Alice # Using get() - safer (no error if key missing) print(person.get("age")) # 25 print(person.get("email")) # None print(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.py Python
person = {"name": "Alice", "age": 25, "city": "NYC"} # Get all keys print(list(person.keys())) # ['name', 'age', 'city'] # Get all values print(list(person.values())) # ['Alice', 25, 'NYC'] # Get key-value pairs as tuples print(list(person.items())) # [('name', 'Alice'), ...] # Check if key exists print("name" in person) # True print("email" in person) # False
['name', 'age', 'city'] ['Alice', 25, 'NYC'] [('name', 'Alice'), ('age', 25), ('city', 'NYC')] True False

Other Useful Methods

more_methods.py Python
d1 = {"a": 1, "b": 2} d2 = {"c": 3, "d": 4} # update() - Merge dictionaries d1.update(d2) print(d1) # {'a': 1, 'b': 2, 'c': 3, 'd': 4} # copy() - Create a copy d3 = d1.copy() # clear() - Remove all items d3.clear() print(d3) # {} # len() - Count items print(len(d1)) # 4
{'a': 1, 'b': 2, 'c': 3, 'd': 4} {} 4

Lab Exercise 2: Dictionary Methods

Intermediate

Instructions

Practice using dictionary methods to analyze data.

Your Task

Given inventory = {"apples": 50, "bananas": 30, "oranges": 45}, print all keys, check if "grapes" exists, and print the total count of all items.

Code Editor
Output
Click "Run Code" to see output...

Checkpoint: Methods Mastered!

You know dictionary methods. Let's learn CRUD operations!

Adding, Updating, and Deleting

Dictionaries are mutable - you can change them after creation.

Adding and Updating

adding.py Python
person = {"name": "Alice"} # Add new key person["age"] = 25 person["city"] = "NYC" # Update existing key person["age"] = 26 # Happy birthday! # setdefault() - Add only if key doesn't exist person.setdefault("country", "USA") person.setdefault("name", "Bob") # Won't change - name exists print(person)
{'name': 'Alice', 'age': 26, 'city': 'NYC', 'country': 'USA'}

Deleting

deleting.py Python
person = {"name": "Alice", "age": 25, "city": "NYC"} # del - Delete by key del 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.py Python
scores = {"Alice": 95, "Bob": 87, "Charlie": 92} # Iterate over keys (default) for name in scores: print(name) # Iterate over values for 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.py Python
# Create dict from lists names = ["Alice", "Bob", "Charlie"] scores = [95, 87, 92] grades = {name: score for name, score in zip(names, scores)} print(grades) # Transform values doubled = {k: v * 2 for k, v in grades.items()} print(doubled) # Filter with condition passing = {k: v for k, v in grades.items() if v >= 90} print(passing)
{'Alice': 95, 'Bob': 87, 'Charlie': 92} {'Alice': 190, 'Bob': 174, 'Charlie': 184} {'Alice': 95, 'Charlie': 92}

Lab Exercise 4: Iteration

Intermediate

Instructions

Practice iterating through dictionaries.

Your Task

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.

Creating Nested Structures

nested.py Python
students = { "alice": { "name": "Alice Smith", "grades": {"math": 95, "science": 92}, "active": True }, "bob": { "name": "Bob Jones", "grades": {"math": 88, "science": 85}, "active": True } } # Access nested values print(students["alice"]["name"]) print(students["alice"]["grades"]["math"])
Alice Smith 95

Working with Nested Data

nested_ops.py Python
# Update nested value students["alice"]["grades"]["english"] = 90 # Loop through nested structure for 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!

Chapter 6 Summary

Congratulations! You've mastered Python dictionaries. Let's recap:

Key Takeaways

Key-Value Pairs

Access values by unique keys. Use get() for safe access.

Methods

keys(), values(), items() for iteration. update() to merge.

CRUD

Add/update with [], delete with del or pop().

Iteration

for key, value in dict.items() is the Pythonic way!

Chapter 6 Complete!

You've mastered dictionaries. Ready to prove your skills?

Take the Chapter 6 Practical Exam