Python Chapter 6: Dictionaries

Master Python's most powerful data structure through interactive exploration

Dictionary Basics

What is a Dictionary?

A dictionary is an unordered collection of key-value pairs. Each key must be unique and immutable (strings, numbers, or tuples), while values can be of any type.

# Creating dictionaries empty_dict = {} student = {"name": "Alice", "age": 20, "grade": "A"} mixed = {1: "one", "two": 2, (3, 4): "tuple key"} # Dictionary constructor person = dict(name="Bob", age=25, city="NYC")

Accessing Values

Method Syntax When Key Missing Best Use
dict[key] student["name"] Raises KeyError When key must exist
dict.get(key) student.get("name") Returns None When key might not exist
dict.get(key, default) student.get("gpa", 0.0) Returns default When you need a fallback
# Accessing examples student = {"name": "Alice", "age": 20} # Using bracket notation print(student["name"]) # "Alice" print(student["grade"]) # KeyError! # Using get() print(student.get("name")) # "Alice" print(student.get("grade")) # None print(student.get("grade", "N/A")) # "N/A"

Adding and Updating

# Adding new key-value pairs student["grade"] = "A" student["gpa"] = 3.8 # Updating existing values student["age"] = 21 # Using update() for multiple changes student.update({"age": 22, "major": "CS"})

Dictionary Comprehensions

# Basic comprehension squares = {x: x**2 for x in range(1, 6)} # {1: 1, 2: 4, 3: 9, 4: 16, 5: 25} # With condition evens = {x: x**2 for x in range(10) if x % 2 == 0} # From two lists keys = ["a", "b", "c"] values = [1, 2, 3] combined = {k: v for k, v in zip(keys, values)}

Key Points

  • Dictionary keys must be immutable (strings, numbers, tuples)
  • Keys are unique - adding a duplicate key updates the value
  • Dictionaries are mutable - you can change them after creation
  • Since Python 3.7, dictionaries maintain insertion order

Dictionary VisualizerInteractive

Add, update, and remove key-value pairs to see how dictionaries work visually.

Visual Representation:

Dictionary is empty. Add some key-value pairs above!

Python Code:

my_dict = {}

Dictionary Length:

len(my_dict) = 0

Dictionary Methods PlaygroundInteractive

Current Dictionary:

sample_dict = { "name": "Alice", "age": 25, "city": "NYC", "job": "Engineer" }

Try Dictionary Methods:

Output:

Click a method button to see it in action!

Explanation:

Method explanations will appear here...

Common Dictionary Methods

  • keys() - Returns a view of all keys
  • values() - Returns a view of all values
  • items() - Returns a view of all (key, value) tuples
  • get(key, default) - Returns value or default if key doesn't exist
  • pop(key) - Removes and returns value for key
  • popitem() - Removes and returns last (key, value) pair
  • update(dict) - Updates dictionary with another dictionary
  • setdefault(key, default) - Returns value if exists, else sets and returns default
  • clear() - Removes all items from dictionary

How Dictionaries Work: Hash TablesEducational

Dictionaries use hash tables for fast lookups. Each key is converted to a hash (number) that determines which "bucket" stores the key-value pair.

Hash Table (8 buckets):

Hash Calculation:

Enter a key above to see how it's hashed and placed in a bucket. Python's hash() function converts keys to integers. The bucket index = hash(key) % number_of_buckets

Why Dictionaries Are Fast

  • O(1) Average Lookup - Finding a value by key is nearly instant
  • Hash Function - Converts keys to array indices
  • Collision Handling - When two keys hash to same bucket, Python handles it efficiently
  • Dynamic Resizing - Table grows automatically when it gets too full
# Hash function examples (simplified) hash("hello") # Large integer (varies by session) hash(42) # 42 (integers hash to themselves) hash((1, 2)) # Tuples are hashable # These raise TypeError (not hashable): # hash([1, 2]) # Lists are mutable # hash({"a": 1}) # Dicts are mutable

Nested DictionariesAdvanced

Dictionaries can contain other dictionaries as values, creating hierarchical data structures perfect for JSON-like data.

# Nested dictionary example students = { "student1": { "name": "Alice", "age": 20, "grades": {"math": 95, "english": 88} }, "student2": { "name": "Bob", "age": 22, "grades": {"math": 78, "english": 92} } } # Accessing nested values print(students["student1"]["name"]) # "Alice" print(students["student1"]["grades"]["math"]) # 95 # Safely accessing with get() print(students.get("student3", {}).get("name", "Not found"))

Interactive Nested Dictionary:

Tree View:

Parse the JSON above to see the tree structure...

Access Path Examples:

Will show access paths after parsing...

Iterating Over Nested Dictionaries

# Iterate through nested structure for student_id, student_data in students.items(): print(f"Student ID: {student_id}") for key, value in student_data.items(): if isinstance(value, dict): print(f" {key}:") for sub_key, sub_value in value.items(): print(f" {sub_key}: {sub_value}") else: print(f" {key}: {value}")

Best Practices

  • Use get() for safe access to avoid KeyErrors
  • Check types with isinstance() before processing
  • Consider using defaultdict for automatic initialization
  • JSON module is perfect for loading/saving nested dictionaries

Sets: Unordered Collections of Unique Items

Sets are like dictionaries with only keys (no values). They're perfect for membership testing and removing duplicates.

# Creating sets empty_set = set() # Can't use {} - that's an empty dict! fruits = {"apple", "banana", "orange"} numbers = set([1, 2, 2, 3, 3, 3]) # {1, 2, 3} - duplicates removed # Set operations a = {1, 2, 3, 4} b = {3, 4, 5, 6} union = a | b # {1, 2, 3, 4, 5, 6} intersection = a & b # {3, 4} difference = a - b # {1, 2} symmetric_diff = a ^ b # {1, 2, 5, 6}

Set Operations Playground:

Result:

Click an operation button to see the result!

Visualization:

Results will be visualized here

Set Methods

# Adding and removing fruits = {"apple", "banana"} fruits.add("orange") # Add single item fruits.update(["grape", "kiwi"]) # Add multiple items fruits.remove("banana") # Remove (raises KeyError if not found) fruits.discard("mango") # Remove (no error if not found) fruits.pop() # Remove and return arbitrary item fruits.clear() # Remove all items

Set Comprehensions

# Set comprehension syntax squares = {x**2 for x in range(10)} # {0, 1, 4, 9, 16, 25, 36, 49, 64, 81} # With condition even_squares = {x**2 for x in range(10) if x % 2 == 0} # {0, 4, 16, 36, 64} # Remove duplicates from list numbers = [1, 2, 2, 3, 3, 3, 4] unique = {x for x in numbers} # {1, 2, 3, 4}

When to Use Sets vs Dictionaries

Feature Set Dictionary
Structure Unordered unique items Key-value pairs
Lookup Speed O(1) - Fast O(1) - Fast
Use Case Membership testing, remove duplicates Store related data with keys
Duplicates Not allowed Keys must be unique
Ordering Unordered (before 3.7) Insertion order (3.7+)

Knowledge Check QuizTest Yourself

Test your understanding of Python dictionaries and sets!

Course Home