Master Python's most powerful data structure through interactive exploration
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")
| 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 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"})
# 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)}
Add, update, and remove key-value pairs to see how dictionaries work visually.
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 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
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"))
# 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}")
get() for safe access to avoid KeyErrorsisinstance() before processingSets 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}
# 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 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}
| 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+) |
Test your understanding of Python dictionaries and sets!